【发布时间】:2014-05-26 18:46:12
【问题描述】:
我正在尝试使用本机消息向我的本机 Windows 应用程序发送一些数据。它适用于 runtime.sendNativeMessage() 方法。当我尝试使用使用端口的长期连接时,它还可以将数据从 chrome 传递到我的应用程序。但是,chrome 扩展只能接收来自我的应用程序的第一个响应。我确信端口仍然打开,因为我的应用程序仍然可以从 chrome 接收数据。以下是我的代码:
Chrome 扩展脚本:
var port = chrome.runtime.connectNative('com.mydomain.app1');
port.onMessage.addListener(function(msg) {
console.log("Received from port:", msg);
});
port.onDisconnect.addListener(function() {
console.log("Disconnected");
});
chrome.tabs.onUpdated.addListener(
function(tabId, changeInfo, tab) {
var param = {};
param['url'] = tab.url;
port.postMessage( param);
}
}
我在 c++ 中的 windows 应用程序:
int _tmain(int argc, _TCHAR* argv[])
{
while( true )
{
//read the first four bytes (=> Length)
unsigned int length = 0;
for (int i = 0; i < 4; i++)
{
char c;
if( ( c=getchar()) != EOF)
length += c<<i*8;
else return 0;
}
//read the json-message
std::string msg = "";
for (int i = 0; i < length; i++)
{
msg += getchar();
}
//.... do something
//send a response message
std::string message = "{\"text\": \"This is a response message\"}";
unsigned int len = message.length();
// We need to send the 4 bytes of length information
std::cout << char(((len>>0) & 0xFF))
<< char(((len>>8) & 0xFF))
<< char(((len>>16) & 0xFF))
<< char(((len>>24) & 0xFF));
// Now we can output our message
std::cout << message.c_str();
std::cout.flush();
}
}
请注意最后一行“std::cout.flush();”,如果我将其注释掉,即使是第一个响应也不会在 chrome 中显示。我只是不知道 chrome 如何从应用程序的标准输出中读取数据。
【问题讨论】:
-
只是一个更正:上面的代码实际上是有效的。我的实际代码包含响应消息的一些准备工作。这就是问题所在。请查看我对 Almog 答案的评论。
标签: windows google-chrome-extension chrome-native-messaging