.NET应用程序与Google Chrome扩展程序的交互

时间:2014-03-25 13:30:34

标签: .net google-chrome-extension ipc

我有一个关于浏览器远程控制的问题。我的主要目标是从Google Chrome中读取所有打开的标签网址,并在找到匹配的网址时关注标签页并重新加载当前页面。所有这些东西都是从本机应用程序调用的(而不是从Chrome到本机应用程序。

目前,我已尝试使用Win32-API的东西(FindWindowEx,...),新的.NET Automation,但这只是给我什么(前者)或只有当前标签的URL (后者)。

所以我认为 - 基于研究 - 编写Google Chrome扩展程序并以这种方式进行交互是最好的主意。令人遗憾的是:不再支持NPAPI扩展,现在只支持JavaScript类型的东西。

然后我尝试使用nativeMessaging进行通信,但我无法正常工作(永远不会以某种方式执行),而关于此的文档部分是-censored - 。

这引出了一个问题:如果事情是可能的,如果是的话,它们怎么可能?


在注册表中注册的主机应用程序(Windows):

public static void Main(string[] args)
{
    string message = "{\"text\": \"My response\"}";
    byte[] length = BitConverter.GetBytes(message.Length);
    foreach (byte b in length)
    {
        Console.Write((char)b);
    }
    Console.Write(message);
}

主机应用程序的清单

{
  "name": "My.ChromeHost",
  "description": "This extension is used for browser interaction with My App.",
  "version": "1.0",
  "path": "C:\\Program Files (x86)\\My Company AG\\My Product\\My.ChromeHost.exe",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://bejoalmncckddamdhnfjafipbgflolmk"
  ]
}

扩展名单

{
  "manifest_version": 2,
  "name": "My App",
  "description": "This extension is used for browser interaction with My App.",
  "version": "1.0",
  "background": {
    "scripts": [
        "background.js"
    ],
    "persistent": false
  },
  "permissions": [
    "tabs",
    "nativeMessaging"
  ]
}

background.js

// sending a message to the app (altough I need it vice versa)
var port = chrome.runtime.connectNative("My.ChromeHost");
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
port.postMessage({ "text": "My request" });

function onNativeMessage(message) {
    alert("Received message: <b>" + JSON.stringify(message) + "</b>");
}

function onDisconnected() {
    alert("Failed to connect: " + chrome.runtime.lastError.message);
    port = null;
}

1 个答案:

答案 0 :(得分:1)

我设法建立了与我的本机应用程序的连接,但没有使用本机消息传递。我切换到SignalR进行通信。自托管的SignalR主机在我的应用程序中运行,并且扩展充当客户端,一旦启动就会注册。然后,IPC可以从双方进行,这足以满足我的要求。

更新:根据请求,此处有一个小样本应用程序:

http://tooldesign.ch/pub/SignalRChrome.zip

请查看https://developer.chrome.com/extensions,了解有关如何开发,打包和分发Chrome扩展程序的信息。由于私钥,这不包含在我的示例项目中。