QFDev
QFDev

Reputation: 9008

Selectively include javascript file dependent on website

I'm trying to build a Chrome Extension that will work with two websites, we'll call them website1.com and website2.com. Depending on what website we are on I would like to include a different JS file that will store all the logic (In this example I have called it code-for-website-1.js (there would also be another JS for website2.com).

I'm having a problem figuring out how I can only include code-for-website-1.js when I am on website1.com and code-for-website-2.js when I am on code-for-website-2.js.

Here is my manifest:

{
  "name": "My Chrome Extension",
  "version": "1.0",
  "description": "Extension description",
  "manifest_version": 2,
  "permissions": ["tabs", "http://www.website1.com", "http://www.website2.com"],
  "content_scripts": [
    {
      "matches": ["http://www.website1.com"],
      "js": ["jquery.js", "code-for-website-1.js"]
    }
  ]
}

I tried to use one controller.js that would use the following command:

if (onWebsite1 == true){
chrome.tabs.executeScript(null, { file: "code-for-website-1.js" });
} else {
chrome.tabs.executeScript(null, { file: "code-for-website-2.js" });
}

With this I just get the error:

Uncaught TypeError: Cannot call method 'executeScript' of undefined

Upvotes: 0

Views: 331

Answers (1)

Josh
Josh

Reputation: 3284

in the manifest according to the documentation you can add multiple objects to the content_script array

example

"content_scripts": [
   {
      "matches": ["http://www.website1.com/*"],
      "js": ["script_for_website1.js"]
   },
   {
      "matches":["http://www.website2.com/*"],
      "js":["script_for_website2.js"]
   }
]

Upvotes: 2

Related Questions