'Un-overwrite a JavaScript function

I made UserScripts, and am now stuck.

Inside of my HTML there is a script tag, and inside the script tag there is the following:

<script>
   setTimeout = function(){}
</script>

There is no way to use the function, its useless.

How can I solve this?

I was thinking using a way to set the function like main = setTimeout() and I can reset it after the script is loaded. Back to like setTimeout = main.

I am also trying to stay (mostly) undetected unlike running all of the code in a different environment like an iframe. I know you can just use setInterval and then break the loop, but this is just an example.



Solution 1:[1]

Run your userscript before the page has a chance to overwrite it. Use // @run-at document-start in the metadata block (combined with instant script injection in the Advanced section of Tampermonkey's config), and then you could do, in your userscript:

const origSetTimeout = window.setTimeout;
// proceed with your script, referencing origSetTimeout

which will continue to work even after the page loads and has overwritten the original setTimeout. (While you could reassign window.setTimeout back to the original one later, that would be detectable - if that's really a concern.)

The variables declared in the userscript, even at the top level, will not leak out into the page scope, so don't worry about origSetTimeout being exposed - though other actions done in the userscript could be detected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance