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.
Greasemonkey user scripts are written in JavaScript and manipulate the contents of a web page using the Document Object Model interface.
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.
A userscript (or user script) is a program, usually written in JavaScript, for modifying web pages to augment browsing.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With