我正在制作我的第一个 Chrome 扩展程序,并注意到从我的 popup.html 页面发送的消息在我的 content.js 消息事件侦听器中重复。我在每条消息发送之前控制台记录了“发送消息”,在每条消息之前记录了“收到消息”,并且我不明白消息是如何复制的。我还检查了 chrome 开发文档中的 sendMessage 和 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://*/*"]
}
}
添加“返回true;”事件处理程序将阻止您的代码一次又一次触发:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action == "show_alert") {
alert(request.alert);
return true;
}
});
当我使用多个框架运行扩展时遇到同样的问题。 @Wayne Smallman 解决方案对我有用:
建议在清单文件中将 all_frames 设置为 false
请确保只注入一次脚本——包含 chrome.runtime.onMessage.addListener() 的脚本。
我犯的错误是,每次发送消息时,我也在重复注入脚本,就像这样:
ChromeService.execInActiveTab((tab) => {
// @ts-ignore
chrome.scripting.executeScript({
target: {tabId: tab.id},
files: ["assets/js/autofill.js"],
}, () => {
// @ts-ignore
chrome.tabs.sendMessage(tab.id, {setDropdownValue: {fieldId: fieldId, fieldValue: value}});
});
});
简单地分离脚本注入和消息发送的逻辑就解决了我的问题。