我有我的pop-up script用于计算页面上单词数的 chrome-extension。因此,当我单击插件工具栏图标时,它开始加载并向 content-script
发送消息,作为返回,content-script
会回复页面上的字数信息。
var Popup = (function () {
function Popup() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var message = {};
chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
alert("!"); // I can see this alert many times (1..4)
var count = response.data;
if (count != 1) {
document.getElementById("word-count").innerText = count;
}
});
});
}
return Popup;
})();
new Popup();
问题在于 sendMessage
调用了多次(当弹出脚本本身仅加载一次时)。
有时它会调用 sendMessage
1 次,有时会调用 2、3、4 次,但对于某些页面(如堆栈溢出站点)仅调用一次。
问:我想知道为什么会发生这种情况?
更新:
仅供引用:我仅拥有一个/事件选项卡的权限,这是我的 manifest.json
中的内容:
"permissions": [
"<all_urls>",
"activeTab",
"storage"
]
内容脚本部分:
"content_scripts": [
{
"matches": ["*://*/*"],
"css": ["css/content.css"],
"all_frames" : true,
"js": [
"lib/jquery/jquery.min.js",
"lib/jquery/jquery.min.map",
"src/msg/IMessage.js",
"src/msg/IMessage.ts",
"src/content/IFrame.js",
"src/content/IFrame.ts",
"src/content/Content.js"
]
}
],
最佳答案
来自https://developer.chrome.com/extensions/tabs#method-sendMessage :
Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension.
这意味着如果<iframe>
中有一个内容脚本正在运行选项卡上的 s,这些也将被执行。
关于javascript - Chrome 扩展中的弹出脚本多次发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30267066/