chrome.runtime.connectNative generates Uncaught TypeError: undefined is not a function

前端 未结 1 1668
情歌与酒
情歌与酒 2021-02-20 02:18

I did write an chrome extension that calls this connect() function to connect to a local C++ program:

function connect() {
  console.log(\"test1\");
  //port = c         


        
相关标签:
1条回答
  • 2021-02-20 02:46

    connectNative() is not available in a content scripts. To connect to a local program the content script must send the data e.g. to the background script of the extension and in the background script, port = chrome.extension.connectNative can be used. So here a solution:

    contentscript.js:

    ....
    // send data to background script
    chrome.extension.sendRequest("Some Data");
    ....
    

    background.js:

    function connect() {
        // connect to local program com.a.chrome_interface
        port = chrome.extension.connectNative('com.a.chrome_interface');
        port.onMessage.addListener(onNativeMessage);
        port.onDisconnect.addListener(onDisconnected);
    }
    
    chrome.extension.onRequest.addListener(function(data, sender) {
        if (data.length > 0) {
            connect();
            sendNativeMessage(data);
        }
    });
    

    manifest.json as above in my question but additionaly:

    ...
      "background": {
      "scripts": ["background.js"]
      },
    ...
    

    com.a.chrome_interface.json is unchange as in the question above.

    0 讨论(0)
提交回复
热议问题