javascriptbrowserxssexploit

Why does an empty method works like a sink in JavaScript?


I define object a with an empty method b(). The method has no parameter and does nothing!

Please someone tell me, why when I call a.b() and pass JS code as a parameter, does it execute the code?

var a = {
  b() {}
}

a.b('' - alert(1) - '');

It works like a sink for example eval, setInterval, setTimeout and give JS code and execute it!


Solution

  • Maybe your misunderstanding is because of the syntax.

    If you think about what you are passing to a.b() and only put this into the console, you will see:

    > ''-alert(1)-''
    NaN
    

    because you are doing some "mathematics" here: an empty string '' minus the return of the funtion call alert(1) (which returns undefined) and then minus another empty string.

    If you did the same with plus, javascript would concat everything into a single string:

    > ''+alert(1)+''
    "undefined"
    

    So basically, your code is executed before anything is passed to the function a.b. If you don't want this to happen, you would have to properly quote the call to alert(1) in one of the following ways:

    'alert(1)'
    "alert(1)" // but not ''alert(1)''
    `alert(1)`
    

    It has therefore nothing to do with your function specifically.