In the background page of my Chrome extension I need to do the following:
- create a tab with an html page that resides in my extension folder or that is dynamically generated by the background page;
- once the new tab is loaded, inject a content-script in it in order to use message passing;
- once the script has been injected, send a message to the new tab with some data.
This always turns into the error:
tabs.executeScript: Cannot access contents of url "". Extension manifest must request permission to access this host.
or, if the page or script are stored into .html and .js dedicated files in my extensions folder:
tabs.executeScript: Cannot access contents of url "chrome-extension://ehdjfh.../page.html". Extension manifest must request permission to access this host.
The error is generated when chrome.tabs.executeScript()
is executed and the content-script injection is blocked. (I would need this structure to pass some big data to the tab that will be truncated if passed directly as string into the coded html url)
Here is a code sample that can be used to test the behavior into a working extension, just copy-paste and load the extension in Chrome:
background.js
chrome.browserAction.onClicked.addListener(function() {
var getSampleHTML = function() {
return 'javascript:\'<!doctype html><html>' +
'<head></head>' +
'<body>' +
'<p id="myId">page created...</p>' +
'</body>' +
'</html>\'';
};
// create a new tab with an html page that resides in extension domain:
chrome.tabs.create({'url': getSampleHTML(), 'active': false}, function(tab){
var getSampleScript = function() {
return 'chrome.extension.onRequest.addListener(' +
'function(request, sender, sendResponse) {' +
'if(request.action == "print_data" && sender.tab.id == ' + tab.id + '){' +
'var p = document.getElementById("myId");' +
'p += "<br>data received: " + request.data;' +
'}' +
'});'
'document.getElementById("myId").innerHTML += "<br>content-script loaded...";'
};
// inject the content-script in the page created:
chrome.tabs.executeScript(tab.id, {code: getSampleScript()}, function(){
// send the data to the content-script:
chrome.tabs.sendRequest(tab.id, {action: "print_data",
data: "some long data"});
});
});
});
manifest.json
{
"name": "ContentScript Injection Sample",
"description": "",
"version": "0.1",
"permissions": ["tabs"],
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "open a new tab and inject contentscript"
},
"manifest_version": 2
}