【问题标题】:how to handle chrome.runtime.sendNativeMessage() in native app如何在本机应用程序中处理 chrome.runtime.sendNativeMessage()
【发布时间】:2013-11-27 08:49:19
【问题描述】:

我正在开发本地消息传递主机。我可以使用 api 启动我的自定义应用程序

var port = chrome.runtime.connectNative('com.my_company.my_application');

我可以使用 api 将消息发布到我的自定义应用程序

port.postMessage({ text: "Hello, my_application" });

我知道他们正在使用输入/输出流来发送和接收消息。 我的本机应用程序(c 或 c++ exe)应该如何收到有关收到消息的通知 我应该处理哪个函数/事件来接收消息。

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    更新:

    关于如何在原生应用上监听消息,它们被发送到 stdio(目前这是 Chrome 扩展程序和原生应用之间唯一可用的通信通道)。 看看这个 sample app 以原生消息主机 implemented in python 为特色。


    您在端口的 onMessage event 上侦听注册侦听器的消息。

    仅当您需要一次性通信(不是永久端口)时才使用 sendNativeMessag()。在这种情况下,不要使用chrome.runtime.connectNative(...)。相反,请执行以下操作:

    var msg = {...};
    chrome.runtime.sendNativeMessage("<your_host_id>", msg, function(response) {
        if (chrome.runtime.lastError) {
            console.log("ERROR: " + chrome.runtime.lastError.message);
        } else {
            console.log("Messaging host sais: ", response);
        }
    });
    

    关于 Native Messaging 的文档部分非常详细,是一个很好的信息来源。

    【讨论】:

    • 感谢您的回复。我想知道我的本机应用程序(c 或 c++ exe)将如何接收 chrome.runtime.sendNativeMessage() api 发送的消息。我应该在我的本机应用程序中处理哪个事件来获取此消息。我应该在我的本机应用程序(c 或 c++ exe)中从哪里获取消息。
    • @Nik:我很可能误解了这个问题。请看我更新的答案。
    • @Marc 感谢这项工作.. 最后一件事我想知道什么时候应该关闭 .exe。我应该在标签关闭时发送自定义消息还是有其他任何事情?
    • 您可以检查“getchar()”是否返回 EOF。如果是,请离开循环退出。
    【解决方案2】:

    我正在发布将通信的 c++ 代码,即接收消息并将消息发送到 chrome 扩展。 希望这对其他开发者有所帮助

    int _tmain(int argc, _TCHAR* argv[])
    {
        cout.setf( std::ios_base::unitbuf ); //instead of "<< eof" and "flushall"
        _setmode(_fileno(stdin),_O_BINARY);
    
    
        unsigned int c, i, t=0;
        string inp;  
        bool bCommunicationEnds = false;
    
        bool rtnVal = true;
        do {
    
            inp="";
            t=0;
            //Reading message length 
            cin.read(reinterpret_cast<char*>(&t) ,4);
    
            // Loop getchar to pull in the message until we reach the total
            //  length provided.
            for (i=0; i < t; i++) {
                c = getchar();
                if(c == EOF)
                {
                    bCommunicationEnds = true;
                    i = t;
                }
                else
                {
                    inp += c;
                }
            }
    
             if(!bCommunicationEnds)
            {
                //Writing Message length
                cout.write(reinterpret_cast<char*>(&inp),4); 
                //Write original message.
                cout<<inp;
            }
        }while(!bCommunicationEnds);
        return 0;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2018-07-20
    • 2014-11-20
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多