How to specify different match patterns for multiple content scripts in the manifest.json file of the same extension
Specifying the content_scripts
within manifest.json is a bit limiting. Although you can specify different match patterns, you can only have it execute one possible slew of files.
To achieve what you want, you'll need to set up a background_page
that can interpret page URLs, and execute content scripts as you see fit.
Three different methods might be:
Use the manifest's
content_scripts
to match all possible URLs and execute a simple content script to send a message request to the background page viachrome.extension.sendRequest()
. The background page listens for messages withchrome.extension.onRequest.addListener()
, receives the message, interprets the tab's URL withsender.tab.url
(or have the tab's message sendwindow.location.hostname
, probably easier), then decides what content scripts to inject to the tab viachrome.tabs.executeScript()
.
orJust have your
background_page
listen forchrome.tabs.onCreated.addListener()
andchrome.tabs.onUpdated.addListener()
to get a tab's URL, then decide what content scripts to inject to the tab viachrome.tabs.executeScript()
. No need to specifycontent_scripts
in the manifest for this.
orSimilar to 1, but have your manifest
content_scripts
script figure out what to do based on the current URL (again could interpretwindow.location.hostname
), then usechrome.extension.sendRequest()
with a message for yourbackground_page
stating which content scripts to execute (meaning yourbackground_page
doesn't decide - the original content script does). Same result though.