Basically I'm trying to do a little chrome extension following Google documentation. I'd like to inject a script every time the extension button is clicked. This is my manifest so far:
{
"name": "Example",
"manifest_version": 2,
"version": "1.0",
"permissions": [
"tabs"
],
"description": "My Chrome extension.",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
}
}
And this is my background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {code: "content_script.js"});
});
The problem is that the content_script is not fired, even trying with such a simple alert("aaa");
Can you please tell me what I'm doing wrong? I can't figure it out.
In order to execute a content script on a page, you must request the correct host permissions in your manifest file.
Since you want to insert a content script on click of a browser action button, it suffices to request the activeTab
permission. Furthermore, you can drop the tabs
permission, to reduce the number of permission warnings to zero!
{
"name": "Example",
"manifest_version": 2,
"version": "1.0",
"permissions": [
"activeTab"
],
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
}
}
(The activeTab
permission has been introduced in Chrome 26. If you need to support Chrome 25 and earlier, add the *://*/*
or <all_urls>
permissions to the manifest file).
Note: If you add a callback to chrome.tabs.executeScript
, you would have received a useful error message in chrome.runtime.lastError.message
:
Cannot access contents of url "http....." Extension manifest must request permission to access this host.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {
file: "content_script.js"
}, function() {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With