如何使用C#与Chrome(Chrome扩展程序)进行通信?

我想创建一个可以在我的C#应用​​程序和扩展之间进行通信的桥。
以下是我真正想要的解释:我创建了一个扩展,它将获取HTML元素的详细信息。
但每次启动Chrome时都会启动。 而不是这样做,有没有什么方法可以发送消息到我的chrome扩展,以获取HTML元素的详细信息,然后将其发送回C#应用程序?

我可以使用’XMLHttpRequest’将信息传递给C#,但问题是,当我的页面加载时它就开始了。

让我向你解释我想要的东西:

  1. 当我打开我的chrome时,我的扩展程序将自动启动,并且我的background.cs(背景页面)也会启动。 (这里我想要一些客户端 – 服务器类的通信)

  2. 使用我的C#应用​​程序,我将一些数据发送到chrome扩展(例如StartFetchingDocument)

  3. 一旦我的扩展获得此消息(即StartFetchingDocument),那么我的扩展应该将contect-sctipt.js注入选定的选项卡。

我知道将数据发送回C#需要的其余部分,但是这里我只是在这一阶段陷入困境 – 如何将数据从C#发送到我的扩展(背景页面)。

嗯…可能有更好的方法,但一个简单的方法可能是在你的c#app中打开一个HttpListener并通过扩展程序与它进行通信,如下所示:

var listener = "http://localhost:60024/"; function getCommand(){ var postData = { "action": "getCommand" }; $.post( listener, postData, function(response){ //Parse response and do whatever c# wants }); } function send(data){ var postData = { "action" : "send", "data": data }; $.post(listener, postData); } setInterval(getCommand, 1000); 

在示例中,我使用的是jQuery.post,它可以添加到扩展上下文中,但如果您更喜欢它,可以使用XMLHttpRequest。 而在c#方面:

 using System; using System.Net; namespace HttpListenerTEst { class Program { private static HttpListener _listener; static void Main(string[] args) { _listener = new HttpListener(); _listener.Prefixes.Add("http://localhost:60024/"); _listener.Start(); _listener.BeginGetContext(new AsyncCallback(Program.ProcessRequest), null); Console.ReadLine(); } static void ProcessRequest(IAsyncResult result) { HttpListenerContext context = _listener.EndGetContext(result); HttpListenerRequest request = context.Request; //Answer getCommand/get post data/do whatever _listener.BeginGetContext(new AsyncCallback(Program.ProcessRequest), null); } } } 

在ProcessRequest函数中,您可以读取发布数据或发回一些内容。

获取发布数据:

  string postData; using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { postData = reader.ReadToEnd(); //use your favourite json parser here } 

并发回一些东西:

  string responseString = "This could be json to be parsed by the extension"; HttpListenerResponse response = context.Response; response.ContentType = "text/html"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); 

只是一些快速的头脑风暴,期待更好的想法:)

如果你在RemoteDebugging的调试模式下启动chrome,然后你可以通过指定的端口连接到它,你可能会这样做,但这有点麻烦。

您可以尝试调查Adobe Brackets是如何做到的,但我感觉它是相同的方法。

大多数Google Chrome扩展程序都是用HTML,CSS或Javascript编写的。 然后,将扩展目录捆绑到.crx Chrome扩展文件就像运行简短的Python script一样简单。 但是,C#可以翻译成Javascript,您可以为扩展编写自己的业务逻辑。 看看Script#