I am trying to replace a website's window.onload
function with my own:
window.onload = function () {alert("TEST");};
However, as far as I can tell, it is not working (I get no alert). I have included // @run-at document-end
. I think it is an issue with intercepting window.onload
in time.
I am trying to replace a website's window.onload
function with my own:
window.onload = function () {alert("TEST");};
However, as far as I can tell, it is not working (I get no alert). I have included // @run-at document-end
. I think it is an issue with intercepting window.onload
in time.
2 Answers
Reset to default 3document-end executes the script at DOMContentLoaded event (see also Tampermonkey docs), so if the page is simple the onload event could have already been fired and your function won't run.
In case you want to disable/override window.onload
function of the webpage:
// @run-at document-start
// @grant none
....................
window.onload = function () {alert("TEST");};
The first line will instruct Tampermonkey/Greasemonkey to try to inject your userscript as soon as possible and the second will run your userscript in the context/environment of the webpage, because by default all userscripts run in a separate sandbox with proxied DOM and can't set/call webpage functions and vice versa.
If you already have some @grant
keys use unsafeWindow
instead:
// @run-at document-start
// @grant unsafeWindow
// @grant GM_addStyle
....................
unsafeWindow.onload = function () {alert("TEST");};
Your code should work in most browsers. Try to make shure, that window is not already in loaded state when your code is executed. Following code will be called will call function "onload" even if the window is already loaded.
var onload = function()
{
alert("TEST");
};
if (document.readyState === "plete")
onload();
else
(addEventListener || attachEvent).call(window, addEventListener ? "load" : "onload", onload);