当只发送一条消息时,内容页面上会收到多条消息?
multiple messages are recieved on content page when just one is sent?
当我发送消息四次时,警报被触发!
不知道怎么了!
我也在添加清单。
background.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"});
})
}
});
content.js :
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.method);
if (request.method == "xyz"){
alert("hello);
}
});
这是清单文件
清单:
{
"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"
}
您在 manifest.json
中声明了 "all_frames": true
,这意味着您的内容脚本将被注入到网页中的每个 iframe 中,然后当消息从后台页面发送时,内容脚本中的每个侦听器会对此做出回应。
要解决这个问题,
- 删除
"all_frames"
部分或设置 false
如果您确实希望将脚本注入框架并且只想响应顶部的消息 window,您可以通过检查 window !== window.top
[ 来检测内容脚本=17=]
if (window !== window.top) {
chrome.runtime.onMessage.addListener(callback);
}
或者发送消息时排除iframe:
chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"}, {frameId: 0});
当我发送消息四次时,警报被触发! 不知道怎么了! 我也在添加清单。
background.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"});
})
}
});
content.js :
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.method);
if (request.method == "xyz"){
alert("hello);
}
});
这是清单文件 清单:
{
"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"
}
您在 manifest.json
中声明了 "all_frames": true
,这意味着您的内容脚本将被注入到网页中的每个 iframe 中,然后当消息从后台页面发送时,内容脚本中的每个侦听器会对此做出回应。
要解决这个问题,
- 删除
"all_frames"
部分或设置false
如果您确实希望将脚本注入框架并且只想响应顶部的消息 window,您可以通过检查
window !== window.top
[ 来检测内容脚本=17=]if (window !== window.top) { chrome.runtime.onMessage.addListener(callback); }
或者发送消息时排除iframe:
chrome.tabs.sendMessage(tabs[0].id, {method: "xyz"}, {frameId: 0});