Monday 26 July 2021

Why does function.toString() output "native code", whereas the console displays the function’s source code?

I decided to create a userscript for YouTube live chat. Here is the code:

const toString = Function.prototype.toString

unsafeWindow.setTimeout = function (fn, t, ...args) {
    unsafeWindow.console.log(fn, fn.toString(), toString.call(fn))
    unsafeWindow.fns = (unsafeWindow.fns ?? []).concat(fn)
    return setTimeout(fn, t, ...args)
}

Now look what the output looks like:

enter image description here

The output for some of the functions is predictable, but look at the other ones! When you do just console.log it, you will see the function body, but if you call fn.toString(), you will see function () { [native code] }.

But why? The script is loaded before the page, so the YouTube's scripts couldn't replace the methods.



from Why does function.toString() output "native code", whereas the console displays the function’s source code?

No comments:

Post a Comment