gpt4 book ai didi

google-chrome-extension - chrome.runtime.onMessage 多次调用

转载 作者:行者123 更新时间:2023-12-02 03:52:11 28 4
gpt4 key购买 nike

我创建了一个扩展。当用户点击扩展图标时,它会向内容脚本发送消息,然后内容脚本再次调用一个函数。在该函数中,它将向后台脚本发送消息。我在后台脚本执行多次时遇到一些奇怪的行为 chrome.runtime.onMessage.addListener()。

list .json

{
"manifest_version": 2,
"name": "Reportar",
"version": "1.0",
"description": "Loreipsum.",
"background": {
"scripts": ["bootstrap.js"],
"persistent": false
},
"browser_action": {
"default_icon": "img/icon48.png",
"default_title": "Gitlab Issue"
},
"web_accessible_resources": [
"templates/*.html"
],
"content_scripts": [{
"all_frames": false,
"css": ["content_style.css"],
"js": ["content_script.js"],
"matches": ["http://*/*", "*/*"]
}],
"icons": {
"16": "img/icon20.png",
"48": "img/icon48.png",
"128": "img/icon128.png"
},
"permissions": [
"tabs",
"activeTab",
"<all_urls>",
"storage"
]
}

background.js

function clickOnIssue() {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
console.log('Going to send message to content script that user click on browserAction icon');
chrome.tabs.sendMessage(tabs[0].id, {id: 111});

});
}
chrome.tabs.onUpdated.addListener(function (id, info, tab) {
if (info.status === 'complete') {
chrome.browserAction.onClicked.removeListener(clickOnIssue);
chrome.browserAction.onClicked.addListener(clickOnIssue);
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
var _t = new Date().getTime();
console.log("Request received for getProjectList(" + _t + ")");
sendResponse({t: _t});
return true;
});

}
});

content_script.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request);
//sendResponse({msg: 'received'});
chrome.runtime.sendMessage({action: 'submitSettings'}, function (resp) {
console.log('Received the message that user click on browserAction icon');
updateProjectDropDown();
});
return true;
});

function updateProjectDropDown() {
console.log('Request dispatch for getProjectList');
chrome.runtime.sendMessage({action: 'getProjectList'}, function (resp) {
console.log(resp.t + ': bootstrap.js JS received the message');
});

}

This is browser's console

This is backgound js console

编辑:添加 list 文件

最佳答案

我认为下面的代码可以解决您的问题

chrome.runtime.onInstalled 运行一次,因此您的监听器不会绑定(bind)多次。

chrome.runtime.onInstalled.addListener(function (details) {
chrome.browserAction.onClicked.addListener(clickOnIssue);
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//TODO: your code
});
});

关于google-chrome-extension - chrome.runtime.onMessage 多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45074850/

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