Abh*_*thi 1 google-chrome-extension google-chrome-devtools
当我发送消息四次时,警报就会触发!不知道出了什么问题!我也在添加清单。
背景.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.method == "123")
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"});
})
}
});
Run Code Online (Sandbox Code Playgroud)
内容.js:
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.method);
if (request.method == "xyz"){
alert("hello);
}
});
Run Code Online (Sandbox Code Playgroud)
这是清单文件清单:
{
"manifest_version" : 2,
"version" : "0.1.0.0",
"name" : "xyz",
"short_name": "xyz",
"permissions" : [" <all_urls>","tabs","storage","notifications","unlimitedStorage","downloads"],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>","http://*/*","https://*/*"],
"js": [
"content.js",
],
"all_frames" : true
}],
"browser_action" : {
"default_title" : "test",
"default_popup" : "popup.html"
},
"devtools_page" : "xyz.html"
}
Run Code Online (Sandbox Code Playgroud)
您已"all_frames": true在 中声明manifest.json,这意味着您的内容脚本将被注入到网页中的每个 iframe 中,然后当从后台页面发送消息时,内容脚本中的每个侦听器都会对此做出响应。
为了解决这个问题,
"all_frames"部分或设置它false如果您确实希望将脚本注入到框架中并且只想响应顶部窗口中的消息,您可以通过检查来检测内容脚本window !== window.top
if (window !== window.top) {
chrome.runtime.onMessage.addListener(callback);
}
Run Code Online (Sandbox Code Playgroud)或者在发送消息时排除 iframe:
chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"}, {frameId: 0});
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |