0

我有一个 Windows 形式的 chrome 本机应用程序(c#)。当我在 chrome 中启用扩展时,它会打开。我们可以管理它仅在单击应用程序 exe 时打开吗?我们怎么能做到这一点?这是c#代码

  private static string OpenStandardStreamIn()
    {
    //// We need to read first 4 bytes for length information
    Stream stdin = Console.OpenStandardInput();
    int length = 0;
    byte[] bytes = new byte[4];
    stdin.Read(bytes, 0, 4);
    length = System.BitConverter.ToInt32(bytes, 0);

    string input = "";
    for (int i = 0; i < length;i++ )    
    {
    input += (char)stdin.ReadByte();
    }

    return input;  
    }

    private static void OpenStandardStreamOut(string stringData)
    {
    //// We need to send the 4 btyes of length information
    string msgdata = "{\"text\":\"" + stringData + "\"}";
    int DataLength = stringData.Length;
    Stream stdout = Console.OpenStandardOutput();
    stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
    stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
    stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
    stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
    //Available total length : 4,294,967,295 ( FF FF FF FF )

    Console.Write(msgdata);
    }

背景.js代码

  var host_name = "com.example.native";
    var port = null;

    connectToNative();
    function connectToNative()
    {
    console.log('Connecting to native host: ' + host_name);
    port = chrome.runtime.connectNative(host_name);
    port.onMessage.addListener(onNativeMessage);
    port.onDisconnect.addListener(onDisconnected);
    sendNativeMessage("test");

}

function sendNativeMessage(msg) {
message = {"text" : msg};
console.log('Sending message to native app: ' + JSON.stringify(message));
port.postMessage(message);
console.log('Sent message to native app: ' + msg);
}

function onNativeMessage(message) {
console.log('recieved message from native app: ' + JSON.stringify(msg));
}

function onDisconnected() {
    console.log(chrome.runtime.lastError);
console.log('disconnected from native app.');
port = null;
}

用于将 chrome 扩展程序与应用程序连接的 Menifest 文件

{
  "name": "com.example.native",
  "description": "Native support for Chrome Extension",
  "path": "NativeApp.exe",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://ajfkjfmkedgcgdckdkmppfblonpeench/"
  ]
}  
4

1 回答 1

2

机主机应用程序的要点是根据需要由 Chrome 打开。如果您手动打开它的实例,它将不会连接到 Chrome。

在伪代码中,您可以在本机应用程序中实现以下逻辑:

if( /* opened by Chrome */ ){
  // Do not show UI
  // Listen for command to show UI
  // Communicate with Chrome
} else {
  if( /* there is an open instance of the app */) {
    // Message that instance to show UI
    // Terminate
  } else {
    // Show error, terminate
  }
}

这个问题可能很有趣。

于 2014-08-28T09:25:05.620 回答