Understanding how Greasemonkey runs user scripts

懵懂的女人 提交于 2019-11-28 09:54:07
Brock Adams

Greasemonkey runs at the DOMContentLoaded event by default. This means that everything will be in the page except for possibly large images and stuff added by some javascripts (scripts that fire on the load event or that AJAX-in content).

If you want to wait until even large media has loaded and "onload" scripts have run, use:

window.addEventListener ("load", Greasemonkey_main, false);

function Greasemonkey_main () {

    //***** PUT YOUR GREASEMONKEY CODE HERE.
}

Do not use unsafeWindow.onload = function(){ ... } or window.onload = function() { /* logic here */ } as others have suggested. These are not only poor practice/won't work in GM, but the unsafeWindow is an unnecessary security risk in this case.



However, dealing with JS-added content:

Since you indicated that the node you care about is added by javascript, waiting for the load event will often not work. JS can add, remove or edit nodes at any time.

The best approach in cases like these is to poll for the element you are interested in ("#mybutton"). See this answer to "Fire Greasemonkey script on AJAX request".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!