多次触发 Chrome 扩展程序消息

Cod*_*lla 6 javascript google-chrome sendmessage google-chrome-extension

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

任何帮助,将不胜感激。

弹出窗口.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>
Run Code Online (Sandbox Code Playgroud)

内容.js

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

弹出窗口.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")
    });
}
Run Code Online (Sandbox Code Playgroud)

背景.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()]
  }]);
});
Run Code Online (Sandbox Code Playgroud)

清单文件

{
    "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://*/*"]
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 4

添加“返回 true;” 事件处理程序将阻止您的代码一次又一次触发:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action == "show_alert") {
    alert(request.alert);
    return true;
  }
});
Run Code Online (Sandbox Code Playgroud)