Understanding how Greasemonkey runs user scripts

纵然是瞬间 提交于 2019-11-27 03:17:37

问题


I'm learning Greasemonkey with the hopes of making some improvements to a webpage.

I think I have a good grasp of JavaScript, but I don't understand at what point in the rendering of the document the Greasemonkey user script is executed.

For instance, what if there is JavaScript natively inside the document that inserts some elements to the page. I want my Greasemonkey script to run only after that JS completes.

Let's say this is the document that I'm trying to modify with Greasemonkey

<html>
 <script>
   //insert a button with id="mybutton"
 </script>
</html>

I want the <script> code to complete before my Greasemonkey script is run, because I want to alter its background color.


回答1:


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".



来源:https://stackoverflow.com/questions/8772137/understanding-how-greasemonkey-runs-user-scripts

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