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

San*_*hah 5 c# google-chrome communication

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

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

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

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

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

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

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

cvi*_*ejo 9

嗯...可能有更好的方法,但一个简单的方法可能是在你的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);
Run Code Online (Sandbox Code Playgroud)

在示例中,我使用的是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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

获取发布数据:

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

并发回一些东西:

        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();
Run Code Online (Sandbox Code Playgroud)

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