In our firefox extension from the background script, we are checking the currently loading tab and check whether the URL is our desired URL if it is our desired URL then we are executing a javascript file on the tab with the help of browser.tabs.onupdated event using browser.tabs.executeScript and the file is executed successfully but the window.onload event present on the content script doesn't execute but the console statement on the first line executed in the content script

Background.js

 browser.tabs.onUpdated.addListener(
    function (tabId, changeInfo, tab) {
        // here checking wether to execute the script for the currently loading tab based on the URL of tab
        browser.tabs.executeScript(tab.id, { file: "jquery.min.js" });
         browser.tabs.executeScript(tab.id, { file: "automate.js" });
      
    },
    { properties: ["status"] }
  );

automate.js

console.log("automate.js executing");
window.addEventListener("load",function(){
// this console.log statement not printed
 console.log("window is loaded");
})
1

There are 1 best solutions below

7
On

By default content scripts run at document_idle:

The document and all its resources have finished loading.

Solution:

It is the same as load event conditions so you don't need it. Simply do what you need right away.

Alternative:

If for some reason you need to do something before the load event and something afterwards, you can use document_end to run the script at DOMContentLoaded event (DOM is ready, resources are still loading) or document_start (DOM is empty, only <html> node is parsed).

browser.tabs.executeScript(tab.id, { file: 'jquery.min.js', runAt: 'document_end' });
browser.tabs.executeScript(tab.id, { file: 'automate.js', runAt: 'document_end' });