我在Windows上遇到了本地消息同步的问题。我正在尝试在backgroundPage和hostApp之间同步消息。通常,我们使用本地消息传递如下:
//popup.js
function appendMessage(text) {
document.getElementById('response').innerHTML += "<p>" + text + "</p>";
}
function sendNativeMessage() {
message = {"command": document.getElementById('input-text').value};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
updateUiState();
}
function connect() {
var hostName = "com.google.chrome.example.dmtest1";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>");
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
updateUiState();
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('connect-button').addEventListener(
'click', connect);
document.getElementById('send-message-button').addEventListener(
'click', sendNativeMessage);
updateUiState();
});
<html>
<head>
<script src='./popup.js'></script>
</head>
<body>
<button id='connect-button'>Connect</button>
<input id='input-text' type='text' />
<button id='send-message-button'>Send</button>
<div id='response'></div>
</body>
</html>
但 sendNativeMessage() 和 onNativeMessage(..) 函数是异步的,我想让它们变成同步的。我尝试了下面的方法,但无法从主机(C++ exe)获取响应数据,并且导致 Chrome 崩溃。
function sendNativeMessage() {
var message = {"command": document.getElementById('input-text').value};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
port.onMessage.addListener(function(msg) {
appendMessage("Receive message: <b>" + JSON.stringify(msg) + "</b>");
});
}
我该如何做到这一点,是否可能,有什么帮助吗?
port.sendMessage
是否存在? - SevenWow