Javascript chrome扩展发送多条消息
你好我正试图向弹出窗口发送消息,但当我关闭弹出窗口时,再次调用它(从上下文菜单)。。它显示了所有最后的弥撒。。 如何仅向新打开的窗口发送一条消息? Manifest.json 1.html 问题 每次调用Javascript chrome扩展发送多条消息,javascript,google-chrome-extension,Javascript,Google Chrome Extension,你好我正试图向弹出窗口发送消息,但当我关闭弹出窗口时,再次调用它(从上下文菜单)。。它显示了所有最后的弥撒。。 如何仅向新打开的窗口发送一条消息? Manifest.json 1.html 问题 每次调用genericOnClick()时,它都会为windows.onCreated事件注册一个新的侦听器。一旦注册,监听器每次都会触发 解决方案 许多可能的解决方案之一是在侦听器第一次被触发时(使用)立即“取消注册”: 哪里调用了genericOnClick()?请将全部代码(或至少所有相关部分)发
genericOnClick()
时,它都会为windows.onCreated
事件注册一个新的侦听器。一旦注册,监听器每次都会触发
解决方案
许多可能的解决方案之一是在侦听器第一次被触发时(使用)立即“取消注册”:
哪里调用了
genericOnClick()
?请将全部代码(或至少所有相关部分)发布。可能将所有代码放在可以帮助ups的位置。。我的错误。。我正在更新代码“sample.js”。我上传的不是选项卡的子集
。与…比较
{
"manifest_version": 2,
"name": "1tst",
"description": "sm txt",
"version": "0.1",
"author": "smwn",
"permissions": [
"activeTab",
"tabs",
"contextMenus"
],
"background": {
"scripts": ["sample.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["1.js"]
}]
}
function genericOnClick(info, tab,selT) {
var vid;
var nw_tb;
chrome.tabs.create({
url: chrome.extension.getURL('1.html'),
active: false
}, function(tab) {
vid = tab.id;
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true
// incognito, top, left, ...
},function(chromeWindow) {
//vid = chromeWindow.id;
}
);
});
chrome.windows.onCreated.addListener(function(tabb){
nw_tb = tabb.id;
alert("vid: "+vid+" nw_tb: "+nw_tb);
chrome.runtime.sendMessage(vid, {statn: selT});
return;
});
}
var title = "Test '%s' menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":["selection"],
"onclick": function(info,tab){ genericOnClick(info,tab, info.selectionText);}
});
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="1.js"></script>
</head>
<body>
</body>
</html>
window.onload=function(){
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
sendResponse({metroSTAT: "OK"});
alert(request.statn);
});
}
// Replace the following block:
chrome.windows.onCreated.addListener(function(tabb){
...
});
// With this:
chrome.windows.onCreated.addListener(function tmpListener(tabb) {
chrome.windows.onCreated.removeListener(tmpListener);
...
});