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

前端 未结 2 1975
广开言路
广开言路 2021-01-03 10:15

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_app         


        
相关标签:
2条回答
  • 2021-01-03 10:50

    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.

    0 讨论(0)
  • 2021-01-03 10:54

    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;
    }
    
    0 讨论(0)
提交回复
热议问题