我创建了一个扩展。当用户点击扩展图标时,它会向内容脚本发送消息,然后内容脚本再次调用一个函数。在该功能的一侧,它将向后台脚本发送消息。我在后台脚本中执行多次执行chrome.runtime.onMessage.addListener()时会遇到一些奇怪的行为。
的manifest.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');
});
}
编辑:添加清单文件
答案 0 :(得分:0)
我认为波纹管代码可以解决您的问题
chrome.runtime.onInstalled运行一次,因此您的侦听器不会多次绑定。
chrome.runtime.onInstalled.addListener(function (details) {
chrome.browserAction.onClicked.addListener(clickOnIssue);
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//TODO: your code
});
});