chrome.runtime.onMessage 多次调用

Jho*_*hon 3 google-chrome-extension

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

清单.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"
    ]
}
Run Code Online (Sandbox Code Playgroud)

背景.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;
        });

    }
});
Run Code Online (Sandbox Code Playgroud)

内容脚本.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');
    });

}
Run Code Online (Sandbox Code Playgroud)

这是浏览器的控制台

这是后台js控制台

编辑:添加清单文件

SKG*_*SKG 7

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

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
    });
});
Run Code Online (Sandbox Code Playgroud)