【问题标题】:Chrome extension messages firing multiple timesChrome 扩展消息多次触发
【发布时间】:2018-04-17 03:02:40
【问题描述】:

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

任何帮助将不胜感激。

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()]
  }]);
});

ma​​nifest.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://*/*"]
    }

}

【问题讨论】:

  • 您在每次点击时重新插入内容脚本,并且内容脚本每次都会在 onMessage 中注册一个新的函数引用。最简单的解决方案是在内容脚本代码中勾选window.init === true,什么都不做,否则设置该属性并注册监听器。
  • @wOxxOm 很好的解释!这非常有效。由于这个原因,我几天来一直在用我的电脑敲打我的头。谢谢
  • A comment on another question 为我提供了修复,建议在清单文件中将 all_frames 设置为 false。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 2013-09-11
      • 2011-03-01
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 2014-09-10
      相关资源
      最近更新 更多