Reputation: 7156
So I am trying to execute a script from external source like www.script.google.com in background.js. But I get this error -
Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "chrome-devtools://devtools/bundled/devtools.html?&remoteBase=https://chrome…&dockSide=undocked&toolbarColor=rgba(223,223,223,1)&textColor=rgba(0,0,0,1)". Extension manifest must request permission to access this host.
What i am doing is sending message from popup.js to background.js In popup.js -
chrome.runtime.sendMessage({type:"addtask"});
In background.js -
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.type == "addtask")
{
chrome.tabs.executeScript(null,
{file:"https://script.google.com/url of script....."});
}
});
My manifest.json-
{
"name": "Extension",
"version": "0.0.1",
"manifest_version": 2,
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"js": ["jquery.min.js","contentscript.js"],
"matches": ["http://*/*","https://*/*"],
"css" : ["feedback.css"]
}],
"permissions": [
"storage","tabs","https://script.google.com"
],
"web_accessible_resources": ["feedback.js","html2canvas.js","event.js"],
"content_security_policy": "script-src 'self' https://script.google.com/*; object-src 'self'"
}
Upvotes: 21
Views: 24385
Reputation: 808
It's super easy to inject a content script declaratively via manifest.json. The matches property determines what URLs the script can access which can also include the filesystem URL's.
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}],
To learn more about match patterns visit https://developer.chrome.com/extensions/match_patterns
To learn more about injecting scripts https://developer.chrome.com/extensions/content_scripts#pi
Upvotes: 0
Reputation: 19285
While ArtPip suggestion works in this case, often you want to execute a script on a tab or all tabs and correctly handle the error if your permissions don't allow injection on that tab or some of the tabs.
Here is an example of executing a script on all tabs and correctly handling errors:
tabs.forEach(tab => {
chrome.tabs.executeScript(tab.id, { file: filename }, result => {
const lastErr = chrome.runtime.lastError;
if (lastErr) console.log('tab: ' + tab.id + ' lastError: ' + JSON.stringify(lastErr));
});
});
Upvotes: 3