我确实编写了一个 chrome 扩展,它调用这个 connect() 函数来连接到本地 C++ 程序:
function connect() {
console.log("test1");
//port = chrome.extension.connectNative('com.a.chrome_interface');
port = chrome.runtime.connectNative('com.a.chrome_interface');
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
console.log("test5");
}
我可以在控制台中看到 test1,但后来我得到了错误
Uncaught TypeError: undefined is not a function
在行中
port = chrome.runtime.connectNative('com.a.chrome_interface');
我的扩展 list 文件在这里:
{
"name": "CPP_Connect",
"version": "1.0",
"description": "Send data to CPP program",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"permissions": ["contextMenus", "tabs", "nativeMessaging", "<all_urls>"],
"manifest_version": 2
}
我的 com.a.chrome_interface.json 看起来像这样:
{
"name": "com.a.chrome_interface",
"description": "Chrome Native Messaging API Example Host",
"path": "com.a.chrome_interface",
"type": "stdio",
"allowed_origins": [
"chrome-extension://abc.../"
]
}
和 com.a.chrome_interface 是一个 linux 可执行 C++ 文件,它会生成一个文件,如果它被调用并且这个文件永远不会被创建。
我确实把两个文件都放进去了
/etc/opt/chrome/native-messaging-hosts/
所以我猜,我确实正确地注册了我的 C++,但我也猜想,如果我注册错了,我应该得到一个不同的错误。
如果我使用 chrome.extension.connect() 脚本运行低谷并且错误消息消失但没有数据到达我的 C++ 程序。
我确实阅读并尝试按照说明进行操作
https://developer.chrome.com/extensions/messaging#native-messaging
并用谷歌搜索了很多,但我可以找出问题的原因。
我在 Ubuntu 12.04 上使用 Chromium 34。
最佳答案
connectNative()
在内容脚本中不可用。
要连接到本地程序,内容脚本必须发送数据,例如到扩展程序的后台脚本和后台脚本中,port = chrome.extension.connectNative
可以使用。
所以这里有一个解决方案:
内容脚本.js:
....
// send data to background script
chrome.extension.sendRequest("Some Data");
....
背景.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 如上所述在我的问题中,但另外:
...
"background": {
"scripts": ["background.js"]
},
...
com.a.chrome_interface.json
与上面的问题一样不变。
关于google-chrome - chrome.runtime.connectNative 生成未捕获的类型错误 : undefined is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726026/