gpt4 book ai didi

javascript - 单个函数调用 chrome.runtime.sendMessage() 中的多条消息;

转载 作者:行者123 更新时间:2023-11-28 19:55:27 24 4
gpt4 key购买 nike

chrome.runtime.sendMessage();

我想将多条(具体来说是 2 条)消息从 contentscript.js 传递到 popup.js。

此函数不需要其他参数,我只需要 message 参数。

在我的 contentscript.js 中,我有这个:

chrome.runtime.sendMessage(message1);

chrome.runtime.sendMessage(message2);

这是我的 popup.js:

chrome.runtime.onMessage.addListener(function(messsage1){
//code for handling the message
});

chrome.runtime.onMessage.addListener(function(messsage2){
//code for handling the message
});

我想将这两个函数组合成一个函数并处理如下消息:

 chrome.runtime.onMessage.addListener(function(){
// how to write the parameter for this function, I can't use ',' right?
// code for handling the message1, message2
});

我该怎么做?

最佳答案

我会将消息作为 JSON 对象发送,并使用附加属性来指定消息的类型。例如:

chrome.runtime.sendMessage({content: "Message1", type: "m1"});

chrome.runtime.sendMessage({content: "Message2", type: "m2"});

然后您可以将消息监听器合并到一个函数中:

chrome.runtime.onMessage.addListener(function(message) {
if(message.type == "m1") {
console.log("First message: ", message.content);
}
if(message.type == "m2") {
console.log("Second message: ", message.content);
}
}

当然,这只是一个粗略的示例 - 您应该根据扩展的要求定制 JSON 对象的结构,但这是我将使用的模式。

关于javascript - 单个函数调用 chrome.runtime.sendMessage() 中的多条消息;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22662802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com