Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle chrome.runtime.sendNativeMessage() in native app

I am working on native messaging host. I am able to launch my custom application by using api

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

I can post message to my custom app by using api

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

I know they are using input/out stream to send and receive messages. how should my native application(c or c++ exe) will get notify about message received which function/ event should i handle to receive message.

like image 968
Nik Avatar asked Dec 25 '22 17:12

Nik


2 Answers

UPDATE:

Regarding how to listen for the messages on the native app, they are sent to the stdio (for the time being this is the only available communication channel between Chrome extensions and native apps). Take a look at this sample app featuring a native messaging host implemented in python.


You listen for messages registering a listener on port's onMessage event.

Use sendNativeMessag() only if you want a one-time communication (not a persistent port). In that case, do not use chrome.runtime.connectNative(...). Instead, do something like this:

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

The docs' section about Native Messaging is pretty detailed and a great source of information.

like image 158
gkalpak Avatar answered Dec 28 '22 06:12

gkalpak


I am posting c++ code which will communicate i.e receives and sends the messages to chrome extension. Hope this will help to other developer

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;
}
like image 24
Nik Avatar answered Dec 28 '22 05:12

Nik