0

I have a bug in my chrome extension manifest v3. I inject a content script in the page every time chrome.runtime.onInstalled event is triggered. The content script in adding an eventListener in page. The problem is every time I refresh (or remove -> add again) the extension, this content script adds again and again the same eventListener in the page. How can I fix this bug?

Example:

//background.js

chrome.runtime.onInstalled.addListener(async details => {
  const contentScript = chrome.runtime.getManifest().content_scripts[0];

  const tabs = await chrome.tabs.query({
    url: contentScript.matches
  });

  tabs.forEach(async tab => {
    if (tab.status !== 'unloaded' && !bannedURLs.some(url => tab.url.indexOf(url) >= 0)) {
      try {
        chrome.scripting.executeScript({
          target: { tabId: tab.id },
          files: contentScript.js
        });
      } catch (error) {
        console.log('executeScript failed on' + tab.id + ' ' + tab.url, error);
      }
    }
  });
}); 
//content.js
if (typeof iframe === 'undefined') {
  const iframe = true;
  document.addEventListener('click', () => {
    console.log('clicked!')
  })
}

dem.1797
  • 49
  • 1
  • 7

1 Answers1

-1

You can add it directly from the manifest like this

         "content_scripts": [
         {
         "js": ["./assets/lib/jquery/jquery.min.js", 
         "./assets/js/your_custom_code.js"],
         "css": ["./assets/css/your_custom_style.css"],
         "matches": ["domain_to_match/*"],
         "run_at": "document_end"
         }
         ]