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

夙愿已清 提交于 2019-11-28 04:32:32

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

script elements are executed in order. The browser even stops loading DOM content if there are script nodes in the body. This is guaranteed to work, otherwise document.write() would stop working.

So you have two solutions:

  1. Use the onload event to load your code.
  2. Add a script tag as the last element of the page (last thing in the body element). This script will be executed after all other scripts have finished and after the body has been converted to a DOM tree.

You use window.load method.

function addLoadEvent(a) {
    var b = window.onload;
    "function" != typeof window.onload ? window.onload = a : window.onload = function () {
        b && b(),
            a()
    }
}
function init() {
    alert('init');
}
addLoadEvent(init);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!