7

I want to create a bridge which can communicate between my C# application and extension.
Here is the explanation of what I actually want: I have created an extension which will get details of HTML element.
But starts every time I start Chrome. Instead of doing this, is there any way I can send a message to my chrome extension to get HTML element details and then send it back to C# application?

I am able to pass information to C# using 'XMLHttpRequest' but issue is, it got started when my page gets loaded.

Let me explain to you what I want:

  1. When I open my chrome, my extension will start automatically and also my background.cs(background page) will start. (Here I want some client-server kind of communication)

  2. Using my C# application I will send some data to the chrome extension (e.g. StartFetchingDocument)

  3. Once my extention gets this message (i.e. StartFetchingDocument), then my extension should inject contect-sctipt.js to the selected tab.

I know the rest of what I need to send that data back to C#, but here I got stuck only at this one stage - how to send data from C# to my extension (background page).

Riot
  • 15,723
  • 4
  • 60
  • 67
Sanket Shah
  • 461
  • 2
  • 7
  • 17

3 Answers3

12

Hm...there's probably better ways, but an easy way might be opening an HttpListener in your c# app and communicate with it from the extension like this:

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);

In the example i'm using jQuery.post, which can be added to the extension context, but you could use XMLHttpRequest if you like it better. And on the c# side:

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);
        }
    }
}

In the ProcessRequest function you can read post data or send something back.

Get post data:

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

and send back some stuff with:

        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();

Just some quick brainstorming, looking forward to better ideas :)

cviejo
  • 4,388
  • 19
  • 30
  • setInterval(poll, 1000); <- this is not exactly polling :) polling is when you send a request which will not return a response until it's necessary, but the question is good :) – povilasp Dec 19 '12 at 13:50
  • 1
    changed it to the neutral setInterval(getCommand, 1000), @povilasp . cheers :) – cviejo Dec 19 '12 at 14:12
  • Is it possible for you to send me some example for this? Please, as I am very new to this. – Sanket Shah Dec 20 '12 at 08:38
  • @SanketShah, the code above is already a fully working example. Just create an extension or take your existing one and paste the js code in one file. Same goes for the c# part, it's a working console app. Or you can simply paste the code to start the HttpListener and callback function in your app, it's pretty straightforward. – cviejo Dec 20 '12 at 16:59
0

You might be able to do this if you start chrome in debug mode for RemoteDebugging and then you can connect to it via the specified Port, but it's a bit of a hassle.

You could try to investigate how Adobe Brackets does it but i have a feeling it's the same method.

dutzu
  • 3,883
  • 13
  • 19
  • Can you please give me more info about it, as I am very new to this? – Sanket Shah Dec 17 '12 at 13:11
  • Basically at the link i gave you you will find info on how to start chrome in debug mode on a specific port. With that information you can then open http:\\localhost: or a socket to that port and you will have a direct link with chrome. I'm not sure how you can access extensions but opened pages and stuff like that you can. More info on how to do this you will find on Chrome's support forum since it's not something related to C# – dutzu Dec 17 '12 at 15:12
0

Most of google chrome extensions are written in HTML, CSS or Javascript. Then, bundling your extension directory into a .crx Chrome Extension file is as simple as running a short Python script. But, C# could be translated into the Javascript, you can write your own business logic for your extensions. Look at Script#

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Its not like that, I want to create an Automate Tool which can record certain html events like filling up an form and play acordingly, I have everything written in C# for Internet explorer, but for Chrome I really don't have any option how to that? – Sanket Shah Dec 17 '12 at 12:51