0

I know if I want to run a javascript or multiple javascript files on a single url you use this format in the manifest.json.

"content_scripts": [
 {
  "matches": [
    "<all_urls>"
  ],
  "js": ["content.js"]
 }
]

However I would like to know how to run a single javascript file on example.com/test and a totally different javascript file on example.com/shop. Is this possible or would this be accomplished with example.com/* in the manifest.json and have some line in the script checking if url contains 'shop' or something like that?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Genetics
  • 28
  • 8
  • Have you check to add a router in your application? – floverdevel Apr 06 '18 at 19:54
  • @floverdevel no, I have no clue what your talking about 'add a router' could you explain, Thanks – Genetics Apr 06 '18 at 19:58
  • 1
    could you conditionally do logic in your script files based on the url? – Daniel A. White Apr 06 '18 at 19:59
  • From my experience the approach you're outlining is the way you have to go. I was not able to filter on individual URL paths and instead had to match the domain (example.com/*) and then do the 'url contains "shop"' logic in the js. It may not be the most elegant approach but it works. – Zach Sadler Apr 06 '18 at 20:00
  • @DanielA.White Thats what I was thinking I had to do, `if (window.location.href.indexOf('shop') != -1)` would something like this work, or do you have a better example. – Genetics Apr 06 '18 at 20:04
  • See the documentation for content scripts: you can use "matches" key to restrict content scripts to an URL pattern, and you can define multiple "content_scripts" entries with different patterns and js. – wOxxOm Apr 07 '18 at 04:07

1 Answers1

2

Documentation for content_scripts.

Example partial manifest.json:

...
"content_scripts": [
  {
    "run_at": "document_end",
    "matches": [
      "https://*.stackexchange.com/*"
    ],
    "js": [
      "vendor.bundle.js",
      "stackexchange.js"
    ],
    "css": []
  },
  {
    "run_at": "document_start",
    "matches": [
      "https://*.stackoverflow.com/*"        ],
    "js": [
      "vendor.bundle.js",
      "stackoverflow.js"
    ],
    "css": []
  }
],
...
Granga
  • 1,612
  • 1
  • 14
  • 20