1

Say I have two content scripts, codeA.js and codeB.js. I am wondering if it possible to run codeA.js on http://www.example.com and have codeB.js run on http://www.domain.com.

Would it be possible to set my content_scripts in the manifest.json file to:

"content_scripts": [
    {
        "matches": ["http://www.example.com", "http:www.domain.com"],
        "js": ["codeA.js", "codeB.js"]
    }
]

and then have each script check to see which URL the page currently sits at? If so, how would I go about doing this?

UPDATE:
I have tried using the following code

if(document.location == "http://*.google.com/*" || "https://*.google.com/*") {
    alert("you are using google");
} else if(document.location == "http://*.yahoo.com/*" || "https://*.yahoo.com") {
    alert("you are using yahoo!");
}

but I kept getting you are using google.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
null
  • 2,060
  • 3
  • 23
  • 42
  • Check this http://stackoverflow.com/questions/14807832/javascript-simple-regex-to-find-root-domain to match domain, your code does not work. – Exception Sep 03 '14 at 01:11
  • Related: ["How to specify which content scripts which will run on all_frames and which won't?"](http://stackoverflow.com/q/15836420/331508). – Brock Adams Sep 03 '14 at 08:21

2 Answers2

3

Note that content_scripts is an array:

"content_scripts": [
    {
        "matches": ["http://www.example.com/*"],
        "js": ["codeA.js"]
    },
    {
        "matches": ["http://www.domain.com/*"],
        "js": ["codeB.js"]
    }
]
rsanchez
  • 14,467
  • 1
  • 35
  • 46
-1

Make a single script file and check for the domain name like below

if(document.location == domain1){
  // load script file for domain1
} else {
  // load script for other domains
}

AFAIK you cannot mention different content script files for different domains in manifest.json file.

As per the edit of your method, that code does not work. You must check it using regular expression not just == as your domain contains * in between. And script Web Accessible Resources before hand.

Exception
  • 8,111
  • 22
  • 85
  • 136
  • Hi, thanks for the quick answer. Unfortunately, I tried your code and it didn't seem to work (see updated question). Any idea on what went wrong? – null Sep 03 '14 at 01:06
  • @Kootling Script files you are trying to load must be mentioned in Web Accessible Resources before hand. Have you done that? Check this https://developer.chrome.com/extensions/manifest/web_accessible_resources – Exception Sep 03 '14 at 01:08
  • Actually, that page states: `Content scripts themselves do not need to be whitelisted.` So I do not think it is a problem of whitelisting the content script. – null Sep 03 '14 at 01:15
  • @Kootling Ok, but have you placed regex to match domain? – Exception Sep 03 '14 at 01:19