问题
I'm trying to wrap my head around how these extensions work. Right now I'm sending a message from content script to the background. I tried both single messages and a long-lived connection. For each page, the console registers multiple logs...and I have no idea why. The scripts are simple:
content.js
chrome.runtime.sendMessage({hi: "hi"}, function(response) {});
//or
//var port = chrome.runtime.connect({name: "test"});
//port.postMessage({hi: "hi"});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab);
console.log(request.hi);
});
//OR
/*chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
console.log(msg);
});
});*/
manifest.json
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": true
}],
"permissions": [
"tabs",
"<all_urls>"
]
In each case, like I said, I get three logs in the background page. Why? I thought it might be due to the number of tabs I have open but the logs show the sender information and it says it comes from the same tab.
MORE: When I refresh this question, I only get one log entry (one entry per block, as in the first comment). When I refresh google results or the Google extensions API page, I get multiple logs.
来源:https://stackoverflow.com/questions/30802260/chrome-extension-fires-multiple-times-on-one-page