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?
A content script is a part of your extension that runs in the context of a particular web page (as opposed to background scripts which are part of the extension, or scripts which are part of the website itself, such as those loaded using the <script> element).
Adding background script to manifest. Background script can react to browser events and perform certain actions, the background page is loaded when it is needed, and unloaded when it goes idle. To use the background file, declare it as follows in the manifest.
Content scripts A content script is “a JavaScript file that runs in the context of web pages.” This means that a content script can interact with web pages that the browser visits. Not every JavaScript file in a Chrome extension can do this; we'll see why later.
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));
});
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