2

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" ] } 
11
  • 1
    If you don't want to list all the sites in the matches: option, how do you want to decide whether to run it? Commented Oct 31, 2018 at 21:31
  • I want the extension to detect specific websites. When detected, if the user clicks the extension it brings them to a website for coupons Commented Oct 31, 2018 at 21:42
  • So list all the websites in matches:. If the list changes, update the list. I don't see any other option. Commented Oct 31, 2018 at 21:43
  • When I look at code from other coupon extensions they have "matches": ["https://*/*"] in there content_scripts. so there must be a way to do it in the js files Commented Oct 31, 2018 at 21:47
  • The JS may do some kind of pattern match on window.location Commented Oct 31, 2018 at 21:48

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.