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

落花浮王杯 提交于 2019-12-04 02:21: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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!