我已经阅读了文档,但仍然无法正常工作。
这是我的 list :
{
"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"
}
}
我在 content.js 中有一个名为“myFunc”的函数。在 background.js 中,我有一个函数“myHandler”,它由 contextMenus.onClicked 监听器调用。我想从 myHandler 调用 myFunc。我尝试使用 tabs.executeScript 和 tabs.query,但似乎无法调用函数。任何人都可以向我解释我应该如何让 background.js 调用 content.js 中的函数吗?
最佳答案
要从后台页面调用内容脚本中的函数,您首先需要知道选项卡 ID。 contextMenus.onClicked
事件有一个包含该 ID 的 tab
参数。然后使用 message passing去做。
例如,在你的后台页面中:
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab)
chrome.tabs.sendMessage(tab.id, {args: ...}, function(response) {
// ...
});
});
在您的内容脚本中:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse(myFunc(request.args));
});
关于javascript - 来自 background.js 的内容脚本中的 Chrome 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18039277/