If, instead of always having a content script injected based on the URL, you want to directly control when a content script is injected, you can use Programmatic Injection.
JavaScript
chrome.tabs.executeScript({file: "content.js"});
CSS
chrome.tabs.insertCSS({file: "content.css"});
Called from an extension page (e.g. background or popup), and assuming you have permission to inject, this will execute content.js
or insert content.css
as a content script in the top frame of the current tab.
You can execute inline code instead of a file as a content script:
var code = "console.log('This code will execute as a content script');";
chrome.tabs.executeScript({code: code});
You can provide a tab ID (usually from other chrome.tabs
methods or messaging) to execute in a tab other than the currently active.
chrome.tabs.executeScript({
tabId: tabId,
file: "content.js"
});
More options are available in the chrome.tabs.executeScript()
documentation and in other Examples.
Using chrome.tabs.executeScript()
does not require "tabs"
permission, but requires host permissions for the page's URL.
If script injection fails, one can catch it in the optional callback:
chrome.tabs.executeScript({file: "content.js"}, function() {
if(chrome.runtime.lastError) {
console.error("Script injection failed: " + chrome.runtime.lastError.message);
}
});