My injected [removed] runs after the target-page's javascript, despite using run_at: document_start?

后端 未结 4 2012
渐次进展
渐次进展 2021-01-01 19:36

I am having some problem with the order of javascript execution when I use the content script to inject some javascript into the HTML page:

This is my HTML page I us

4条回答
  •  难免孤独
    2021-01-01 20:09

    Injected scripts, with src attributes are executed asynchronously in Chrome.
    Consider this HTML file:

    
        Chrome early script inject, Test Page
        
    
    
    

    See the console.

    where localInject1.js is just:

    console.log("In page's script 1: ", new Date().getTime());
    

    and localInject2.js is:

    console.log("In page's script 2: ", new Date().getTime());
    


    Nominally, the console should show:

    In page's script 1:   ...
    In page's script 2:   ...
    In page:   ...
    


    But frequently, and especially on cache-less reloads, you'll see:

    In page's script 2:   ...
    In page:   ...
    In page's script 1:   ...
    


    Setting s.async = false; makes no difference.


    I'm not sure if this is a bug or not. Firefox also gets the scripts out of order, but seems more consistent about it. There don't seem to be any relevant Chrome bugs, and the specs are unclear to me.


    Work around:

    Scripts with code set by textContent, rather than a file linked by src, execute immediately as you would expect.
    For example, if you changed injector.js to:

    var s = document.createElement ("script");
    s.src = chrome.extension.getURL ("inject.js");
    document.documentElement.appendChild (s);
    
    var s = document.createElement ('script');
    s.textContent = 'console.log ("Text runs correctly!", new Date().getTime() );';
    document.documentElement.appendChild (s);
    
    console.log("Inject finished", new Date().getTime() );
    

    you would see:

    Text runs correctly! ...
    Inject finished ...
    In page
    Inside inject.js
    


    Admittedly this can be a pain in a content script, but it may be all you can do (in Chrome) until this issue is resolved by the W3C and browser vendors.

提交回复
热议问题