Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a content script to load AFTER a page's Javascript has executed?

My extension is supposed to load a content script, searchTopic.js, only after the page it's injected into has already fully loaded (yes, I have set "run_at" to "document_end" in the extension manifest), but in fact it's loading before all the DOM objects have been created (the crucial ones are created via some Javascript in the page). So, the question is, how can I wait until the page's Javascript has executed? Here's my manifest:

"content_scripts": [   {   "run_at": "document_end",   "matches": ["https://groups.google.com/forum/*"],   "js": ["searchTopic.js"]   } ], 
like image 668
FractalBob Avatar asked Dec 17 '12 15:12

FractalBob


People also ask

What is the JavaScript event to execute something after the page has finished loading?

The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.

How do I make sure JavaScript is loaded?

What is the best way to make sure javascript is running when page is fully loaded? If you mean "fully loaded" literally, i.e., all images and other resources downloaded, then you have to use an onload handler, e.g.: window. onload = function() { // Everything has loaded, so put your code here };

How do I open popup content script?

They've set the default shortcut to Ctrl+D . Activating this command will perform a click on the page (or browser) action, opening the popup or whatever the action is configured to do.


1 Answers

"run_at": "document_end" is the equivalent to DOMContentLoaded. That is, it fires after the static HTML is loaded, but before slow images and slow finishing javascript.

So you cannot set a content script to fire after the page's JS, just by setting the manifest alone. You must code for this in the content script itself.

For content scripts, "run_at": "document_end" will fire before the onload event (unlike the default document_idle -- which can fire at unpredictable times).

So, the first step is to wait for the load event with code like this in your content script (searchTopic.js):

window.addEventListener ("load", myMain, false);  function myMain (evt) {     // DO YOUR STUFF HERE. } 


In the case where the script you care about takes a while to finish, you will have to poll for some condition on a case-by-case basis. For example:

window.addEventListener ("load", myMain, false);  function myMain (evt) {     var jsInitChecktimer = setInterval (checkForJS_Finish, 111);      function checkForJS_Finish () {         if (    typeof SOME_GLOBAL_VAR != "undefined"             ||  document.querySelector ("SOME_INDICATOR_NODE_css_SELECTOR")         ) {             clearInterval (jsInitChecktimer);             // DO YOUR STUFF HERE.         }     } } 
like image 191
Brock Adams Avatar answered Oct 14 '22 15:10

Brock Adams