最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Tampermonkey replace window.onload - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question asked Sep 14, 2015 at 19:41 qwrqwr 11.1k6 gold badges71 silver badges115 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

document-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);
发布评论

评论列表(0)

  1. 暂无评论