Matti
Matti

Reputation: 21

Run a chrome extension on specific websites

I'm writing a coupon style chrome extension and i want it to run only on specific websites (over 300 sites). I've read about specifying the sites url in content_scripts but that doesn't seem practical especially if i needed to update it. Here is my script:

Manifest.json

{
      "name": "Example",
      "description": "description",
      "version": "1.0",
      "manifest_version": 2,

      "background": 
      {
        "scripts": ["js/background.js", "js/eventPage.js", "js/jquery- 
         3.2.1.min.js"],
        "persistent":false
      },

      "page_action": {
        "default_icon":"img/32icon.png"
      },

      "content_scripts": [
        {
        "matches": ["https://*/*"],
        "js": ["js/sites_cs.js", "js/jquery-3.2.1.min.js"]
        }
      ],

       "permissions": [
       "tabs",
       "http://*/*",
       "https://*/*",
       "activeTab"
     ]
    }

Upvotes: 2

Views: 6659

Answers (1)

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

You can have an array with the URLs you want to match and programmatically inject your content scripts to the matching webpages only. For example, remove the content_scripts entry of manifest.json file and include this code in the background script:

background.js

// myURLs contains the websites where you want your content script to run
const myURLs = ['www.example1.com','www.anotherone.com','www.athird.one'];

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status == 'complete' && myURLs.some(url => tab.url.includes(url))) {
        chrome.tabs.executeScript(tabId,{file:'js/jquery-3.2.1.min.js'},()=>{
            chrome.tabs.executeScript(tabId,{file:'js/sites_cs.js'});
        });
    }
});

This way you just need to keep the variable myURLs updated with the desired URLs and your content scripts will be injected only on those sites.

Upvotes: 8

Related Questions