Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Greasemonkey script to run both at @run-at document-start AND at @run-at document-end?

For my Greasemonkey script, there is part of the code that should run before the page is loaded (@run-at document-start) and another part of the code that should run after the document is loaded (@run-at document-end).
Is this possible?

  • 1st part of script run
  • page is loaded, document is ready
  • 2nd part of script run

I'd rather not use jQuery for this.

I tried the onload event but it didn't work. I think the event cannot be attached if the document is not there yet?

window.document.onload = function(e){ 
    alert("document.onload" ); 
}
like image 754
Azevedo Avatar asked Oct 09 '14 01:10

Azevedo


People also ask

How do I write a script for Tampermonkey?

To get started, install Tampermonkey. Tap its toolbar icon, and select Add a new script . An editor opens with a default script. There's a bunch of metadata at the top; fill out the @match field to control where the script will run.

What is the difference between Greasemonkey and Tampermonkey?

While Greasemonkey supports Firefox and some other open-source browsers, Tampermonkey supports all the major browsers including Firefox, Chrome, and Safari.

How do I run a Greasemonkey script in Firefox?

Installing the Greasemonkey Extension. Click on the Firefox drop-down menu at the top left of the browser and select Add-ons. Type Greasemonkey into the add-ons search box at the top right of the browser. Find Greasemonkey in the list and click on Install.


1 Answers

The event you want is DOMContentLoaded. Also, that is not how to use the load event.

Here's a complete script that demonstrates the various firing times:

// ==UserScript==
// @name        _Show page start event timing
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*
// @run-at      document-start
// ==/UserScript==
console.log ("==> Script start.", new Date() );

// 1ST PART OF SCRIPT RUN GOES HERE.
console.log ("==> 1st part of script run.", new Date() );

document.addEventListener ("DOMContentLoaded", DOM_ContentReady);
window.addEventListener ("load", pageFullyLoaded);

function DOM_ContentReady () {
    // 2ND PART OF SCRIPT RUN GOES HERE.
    // This is the equivalent of @run-at document-end
    console.log ("==> 2nd part of script run.", new Date() );
}

function pageFullyLoaded () {
    console.log ("==> Page is fully loaded, including images.", new Date() );
}

console.log ("==> Script end.", new Date() );

Typical results:

"==> Script start."                           2014-10-09T01:53:49.323Z
"==> 1st part of script run."                 2014-10-09T01:53:49.323Z
"==> Script end."                             2014-10-09T01:53:49.323Z
"==> 2nd part of script run."                 2014-10-09T01:53:49.385Z
"==> Page is fully loaded, including images." 2014-10-09T01:53:49.487Z
like image 198
Brock Adams Avatar answered Oct 12 '22 23:10

Brock Adams