I've read the documentation but I still haven't been able to get this working.
Here is my manifest:
{
"name":"app",
"version":"0.1",
"manifest_version":2,
"description":"app",
"background":{
"scripts":[
"scripts/modernizr.min.js",
"scripts/background.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://*/*", "http://*/*"],
"js": ["scripts/content.js"],
"run_at": "document_end"
}
],
"permissions":[
"contextMenus",
"tabs",
"http://*/*",
"https://*/*"
],
"icons":{
"16":"images/icon_16.png",
"128":"images/icon_128.png"
}
}
I have a function in content.js called "myFunc". In background.js, I have a function, "myHandler" that is called by a contextMenus.onClicked listener. I want to call myFunc, from myHandler. I tried using tabs.executeScript, and tabs.query, but I can't seem to get the function to be called. Can anyone explain to me how I am supposed to let background.js call a function in content.js?
I've read the documentation but I still haven't been able to get this working.
Here is my manifest:
{
"name":"app",
"version":"0.1",
"manifest_version":2,
"description":"app",
"background":{
"scripts":[
"scripts/modernizr.min.js",
"scripts/background.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://*/*", "http://*/*"],
"js": ["scripts/content.js"],
"run_at": "document_end"
}
],
"permissions":[
"contextMenus",
"tabs",
"http://*/*",
"https://*/*"
],
"icons":{
"16":"images/icon_16.png",
"128":"images/icon_128.png"
}
}
I have a function in content.js called "myFunc". In background.js, I have a function, "myHandler" that is called by a contextMenus.onClicked listener. I want to call myFunc, from myHandler. I tried using tabs.executeScript, and tabs.query, but I can't seem to get the function to be called. Can anyone explain to me how I am supposed to let background.js call a function in content.js?
Share Improve this question asked Aug 4, 2013 at 2:47 Lebowski156Lebowski156 9515 gold badges11 silver badges35 bronze badges1 Answer
Reset to default 17To call a function in the content script from the background page, you first need to know the tab id. contextMenus.onClicked
event has a tab
parameter containing that id. Then use message passing to do it.
For example, in your background page:
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab)
chrome.tabs.sendMessage(tab.id, {args: ...}, function(response) {
// ...
});
});
In your content script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse(myFunc(request.args));
});