Chrome extension fires multiple times on one page

本秂侑毒 提交于 2019-12-13 08:03:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!