0

In my code I need to execute the same script every time I update a google tab. I wrote this code;

chrome.tabs.onActivated.addListener((tab) => {
  chrome.tabs.get(tab.tabId, (current_tab_info) => {
    if (
      current_tab_info.url.search("https://") == 0 &&
      current_tab_info.url.search(".instagram.com/p/") > 0
    ) {
      chrome.tabs.executeScript(null, { file: "./foreground.js" });
    } else {
      console.log("You are not in instagram");
    }
  });
});
chrome.tabs.onUpdated.addListener(function (tabID, changeInfo, tab) {
  if (
    tab.url.search("https://") == 0 &&
    tab.url.search(".instagram.com/p/") > 0
  ) {
    chrome.tabs.executeScript(null, { file: "./foreground.js" });
  } else {
    console.log("You are not in instagram");
  }
});

But executeScript(script) only works on the first "Activate". It does not work on any "Activate" or "Update" after. I want it to execute the script everytime I "Update" the instagram tab,

Note: Manifest v2, Chrome extension.

Also this is foreground.js;

const control = document.getElementById("Tasarruflu Downloader");
console.log("control: " + control);
if (control === null) {
  const button = document.createElement("button");
  button.setAttribute("id", "Tasarruflu Downloader");
  button.innerText = "My Button 1";
  document
    .querySelector("._aamu" && "._ae3_" && "._ae47" && "._ae48")
    .appendChild(button);
  button.addEventListener("click", () => {
    console.log("Pressed a Button");
  });
}

How can i execute script in foreground.js file at onActivated and onUpdated events on my main script?

1 Answers1

0

You could inject your script once when opening a tab or URL by using manifest.json. There is no need on injecting it over and over again - if code inside the script is not changing.

But you need to modify your script and tabs API handlers code. In both places, you need to use runtime. Things that interest you are:

  • send method
  • onMessage event listener

The steps to do it are simple:

  1. send a message via runtime API when the tab would be updated, refreshed, etc.
  2. catch it in the content script by registering onMessage listener
  3. in the callback you could run code shown in the content script example

In order to find what message is sent you could use something like this:

const message = {
name: 'your name for message',
// additional data here
}

Then in the listener callback, you could check if the message has the name you want.

akaras
  • 54
  • 1
  • 7