Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how Greasemonkey runs user scripts

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.

like image 924
Mike Avatar asked Jan 07 '12 18:01

Mike


People also ask

What language does Greasemonkey use?

Greasemonkey user scripts are written in JavaScript and manipulate the contents of a web page using the Document Object Model interface.

How do you make a Greasemonkey script?

In your Firefox window, once you've downloaded and installed Greasemonkey, there'll be a little monkey face in the right-hand corner of the status bar. Right-click on that and you'll get a menu that includes the option "New User Script". Click that and you'll get a dialog looking a bit like the box on the right.

What language are Userscripts written in?

A userscript (or user script) is a program, usually written in JavaScript, for modifying web pages to augment browsing.


1 Answers

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

like image 85
Brock Adams Avatar answered Oct 15 '22 15:10

Brock Adams