Javascript 如何将多个content.js消息路由到多个background.js侦听器?

Javascript 如何将多个content.js消息路由到多个background.js侦听器?,javascript,google-chrome-extension,message-passing,Javascript,Google Chrome Extension,Message Passing,我有一个带有background.js和content.js的Chrome扩展。content.js向background.js发送消息有两次 目前,当我从content.js发送第一个请求时,它会发送到background.js中的两个侦听器。如何告诉请求只转到我想要的后台脚本(因此articleUrl转到第一个侦听器,articleData转到第二个侦听器?) content.js chrome.runtime.sendMessage({ "articleUrl": articleU

我有一个带有background.js和content.js的Chrome扩展。content.js向background.js发送消息有两次

目前,当我从content.js发送第一个请求时,它会发送到background.js中的两个侦听器。如何告诉请求只转到我想要的后台脚本(因此articleUrl转到第一个侦听器,articleData转到第二个侦听器?)

content.js

    chrome.runtime.sendMessage({ "articleUrl": articleUrl }, function (response) {
        console.log("sending articleUrl");
        console.log(response);
    });

button.addEventListener("click", function () {
    chrome.runtime.sendMessage({ "title": title, "image_url": image, "url": url, "snippet": "test" }, function (response) {
        console.log("sending articleData");
        console.log(response);
    });
});
background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("receiving articleUrl");
    console.log(request);
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("recieving articleData");
    console.log(request);
});

仅为消息设置一个侦听器,并根据消息的类型将数据定向到适当的函数。比如:

content.js

chrome.runtime.sendMessage({ "type": "articleUrl", "articleUrl": articleUrl }, function (response) {
    console.log("sending articleUrl");
    console.log(response);
});

button.addEventListener("click", function () {
    chrome.runtime.sendMessage({ "type": "articleData", "title": title, "image_url": image, "url": url, "snippet": "test" }, function (response) {
        console.log("sending articleData");
        console.log(response);
    });
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "articleUrl") {
        // Handle articleUrl
    }
    else if (request.type == "articleData") {
        // Handle articleData
    }
});
background.js

chrome.runtime.sendMessage({ "type": "articleUrl", "articleUrl": articleUrl }, function (response) {
    console.log("sending articleUrl");
    console.log(response);
});

button.addEventListener("click", function () {
    chrome.runtime.sendMessage({ "type": "articleData", "title": title, "image_url": image, "url": url, "snippet": "test" }, function (response) {
        console.log("sending articleData");
        console.log(response);
    });
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "articleUrl") {
        // Handle articleUrl
    }
    else if (request.type == "articleData") {
        // Handle articleData
    }
});

您不能选择侦听器。但是,您可以修改整个方法,请参见