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

问题描述 投票:0回答:1

我有一个带有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);
});
javascript google-chrome-extension message-passing
1个回答
0
投票

仅设置一个消息侦听器,并根据消息的类型将数据定向到适当的功能。类似于:

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);
    });
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type == "articleUrl") {
        // Handle articleUrl
    }
    else if (request.type == "articleData") {
        // Handle articleData
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.