繁体   English   中英

Chrome扩展原生邮件同步

[英]Chrome extension Native messaging synchronization

我在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>");
  });
}

我怎么能这样做,是否有可能,有什么帮助吗?

经过几天的搜索和测试,我终于找到了答案(这里: 如何在本机app中处理chrome.runtime.sendNativeMessage() )并解决了我的问题。 我放弃了使我的回调函数同步的想法,我只是使用另一种方式在Chrome扩展程序backpage和我的本地主机应用程序之间进行通信。 而不是var port = chrome.runtime.connectNative(hostName);port.onMessage.addListener(onNativeMessage);port.postMessage(message); 我使用下面的代码在backpage和hostapp之间发送和接收数据,它是同步的:

chrome.runtime.sendNativeMessage(hostName, sendMsg, function(response) {
            if (chrome.runtime.lastError) {
                alert("ERROR: " + chrome.runtime.lastError.message);
            } else {
                sendResponse({farewell: ParseJSON(response)});
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM