Home > Enterprise >  run js on page load
run js on page load

Time:07-05

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
  });
  }
);

CodePudding user response:

Just add the Attribute onload <body onl oad="reddenPage()"> and the Function will Fire when Body is Loaded.

and Remove all those Chrome Codes they're not Needed.

CodePudding user response:

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

  • Related