gpt4 book ai didi

google-chrome-extension - 如何将消息从 native 应用程序发送到 Chrome 扩展程序?

转载 作者:行者123 更新时间:2023-12-04 03:01:13 24 4
gpt4 key购买 nike

我已阅读文档,但仍然无法实现。
我有用 C 和 Chrome 扩展编写的桌面应用程序。我知道如何在我的 chrome 扩展程序中接收此消息:

port.onMessage.addListener(function(msg) {
console.log("Received" + msg);
});

我应该在我的 C 应用程序中写什么来向我的 chrome 扩展程序发送消息?
Python/NodeJS 示例也是合适的。

最佳答案

为了让原生消息传递主机将数据发送回 Chrome,您必须首先发送四个字节的长度信息,然后将 JSON 格式的消息作为字符串/字符数组发送。

下面是 C 和 C++ 的两个示例,它们分别以略微不同的方式执行相同的操作。

C 示例:

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
// Define our message
char message[] = "{\"text\": \"This is a response message\"}";
// Collect the length of the message
unsigned int len = strlen(message);
// We need to send the 4 bytes of length information
printf("%c%c%c%c", (char) (len & 0xff),
(char) ((len>>8) & 0xFF),
(char) ((len>>16) & 0xFF),
(char) ((len>>24) & 0xFF));
// Now we can output our message
printf("%s", message);
return 0;
}

C++ 示例:
#include <string.h>

int main(int argc, char* argv[]) {
// Define our message
std::string message = "{\"text\": \"This is a response message\"}";
// Collect the length of the message
unsigned int len = message.length();
// We need to send the 4 bytes of length information
std::cout << char(((len>>0) & 0xFF))
<< char(((len>>8) & 0xFF))
<< char(((len>>16) & 0xFF))
<< char(((len>>24) & 0xFF));
// Now we can output our message
std::cout << message;
return 0;
}

(实际消息可以与长度信息同时发送;只是为了清楚起见而将其分解。)

因此,按照 OP Chrome 示例,以下是如何输出消息:
port.onMessage.addListener(function(msg) {
console.log("Received" + msg.text);
});

实际上,不需要使用“文本”作为本地消息传递应用程序返回的键;它可以是任何东西。从 native 消息传递应用程序传递给监听器的 JSON 字符串将转换为 JavaScript 对象。

有关将上述技术与 jsoncpp(C++ JSON 库)结合使用并解析发送到应用程序的请求的原生消息传递应用程序的 C++ 示例,请参见此处: https://github.com/kylehuff/libwebpg/blob/22d4843f41670d4fd7c4cc7ea3cf833edf8f1baf/webpg.cc#L4501

关于google-chrome-extension - 如何将消息从 native 应用程序发送到 Chrome 扩展程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18134665/

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