Search code examples
google-chrome-extension

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.


Solution

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