gpt4 book ai didi

javascript - Chrome 扩展消息多次触发

转载 作者:行者123 更新时间:2023-12-01 17:29:09 25 4
gpt4 key购买 nike

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

内容.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")
});
}

背景.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://*/*"]
}

}

最佳答案

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

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

关于javascript - Chrome 扩展消息多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com