Chrome在background.js的内容脚本中调用函数 [英] Chrome call function in content scripts from background.js
问题描述
我已经阅读了文档,但是仍然无法实现这一功能。
这是我的清单:
{
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:// * / *
,
图标:{
16:images / icon_16.png,
128 :images / icon_128.png
}
}
我有content.js中的一个函数c alledmyFunc。在background.js中,我有一个函数,myHandler由contextMenus.onClicked侦听器调用。我想从myHandler调用myFunc。我尝试使用tabs.executeScript和tabs.query,但我似乎无法获得被调用的函数。任何人都可以向我解释我应该如何让background.js在content.js中调用一个函数?
要从背景页面调用内容脚本中的函数,首先需要知道选项卡标识。 contextMenus.onClicked
事件有一个包含该id的选项卡
参数。然后使用消息传递来完成它。
例如,在你的后台页面中:
chrome.contextMenus.onClicked.addListener(function(info,tab){
if(tab)
chrome.tabs.sendMessage(tab.id,{args:...},function(response){
// ...
});
});
在您的内容脚本中:
<$ p $ (函数(请求,发送者,sendResponse){
sendResponse(myFunc(request.args));
});} $ {code> chrome.runtime.onMessage.addListener
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?
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));
});
这篇关于Chrome在background.js的内容脚本中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!