Monday, June 3, 2024
47
rated 0 times [  50] [ 3]  / answers: 1 / hits: 15615  / 11 Years ago, sun, august 4, 2013, 12:00:00

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?


More From » google-chrome-extension

 Answers
77

To 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));
});

[#76536] Friday, August 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
santiago

Total Points: 375
Total Questions: 106
Total Answers: 97

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;