Search code examples
javascriptgoogle-chromegoogle-chrome-extension

run js on page load


I am trying to make a google chrome extension, and I need JavaScript to run on every page loaded.

I have tried looking everywhere for an answer, but I cannot find one anywhere. Everything is outdated.

This is my current code:

function reddenPage() {
  alert("yay!")
}



chrome.action.onClicked.addListener((tab) => {

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: reddenPage
  });
  }
);

Solution

  • Use chrome.tabs.onUpdated.addListener and then check the TabStatus.

    function reddenPage() {
      alert("yay!")
    }
    
    chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
      // checking status
      if (changeInfo.status === 'complete') {
        chrome.scripting.executeScript({
          target: { tabId },
          func: reddenPage // should be "func" instead of "function"
        });
      }
    });
    

    Note that you don't need { tabId: tabId } because { tabId } is the same. It is called "Shorthand property names".