多次触发Chrome扩展程序消息

时间:2018-04-17 03:02:41

标签: javascript google-chrome google-chrome-extension sendmessage

我正在制作我的第一个Chrome扩展程序,并注意到我的popup.html页面发送的邮件在我的content.js邮件事件侦听器中被复制了。我在每条消息发送之前控制台记录了“发送消息”,并在每条消息之前记录了“收到消息”,我不明白消息是如何被复制的。我还检查了sendMessageonMessage的chrome dev文档,它指定每个sendMessage事件只应触发一次onMessage侦听器。

任何帮助都将不胜感激。

popup.html

<!DOCTYPE html>
<html>
<head>
    <title>Messaging Practice</title>
</head>
<body>
    <h1>Messaging Practice</h1>

    <input type="button" id="send-message" value="Button">
    <script src="popup.js"></script>
</body>
</html>

content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log('message received')
        console.log(request);
    }
);

popup.js

var messageButton = document.querySelector("#send-message");

messageButton.onclick = function() {
    chrome.tabs.query({currentWindow: true, active: true},
    function(tabs) {
        chrome.tabs.executeScript(
            tabs[0].id, {file: "content.js"}
        )
        console.log("sending message")
        chrome.tabs.sendMessage(tabs[0].id, "string message")
    });
}

background.js

chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
  chrome.declarativeContent.onPageChanged.addRules([{
    conditions: [new chrome.declarativeContent.PageStateMatcher({
      pageUrl: {hostEquals: 'stackoverflow.com'},
    })],
        actions: [new chrome.declarativeContent.ShowPageAction()]
  }]);
});

的manifest.json

{
    "name": "Send Messages Practice",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Simple messaging practice with the chrome api",
    "permissions": ["declarativeContent", "activeTab"],
    "background": {
        "scripts": ["background.js"],
        "persistant": true
    },

    "page_action": {
        "default_popup": "popup.html",
        "scripts": ["content.js"],
        "matches": ["http://*/*","https://*/*"]
    }

}

2 个答案:

答案 0 :(得分:1)

返回true;来自事件处理程序的代码将阻止您的代码一次又一次地触发!

答案 1 :(得分:0)

当我使用多个框架运行扩展程序时,遇到相同的问题。 @Wayne Smallman解决方案对我有用:

建议在清单文件中将all_frames设置为false

相关问题