Ameet M.
Ameet M.

Reputation: 11

chrome extension native message not received in c# app

I am trying to communicate between chrome extension and c# app using native messaging. I have refered the link nativeMessaging

In my extension there are 2 menu buttons, one for connectnative and other is postmessage.

When I click on connect native my c# host app(app.exe) gets launched. But after clicking on postmessage no message is received in app.exe.

Below are sample codes

com.ln.json

{
    "name": "com.ln",
    "description": "Chrome Native Messaging API Example Host",
    "path": "app.bat",
    "type": "stdio",
    "allowed_origins":
    [
        "chrome-extension://hplkgmmknmccnfalidkjhkponfakmhag/"
    ]
}

menupopup.js

var port=null;
chrome.browserAction.onClicked.addListener(LinguifyOnClick());
function MenuButtonClicked(evnt)
{
    try
    {
        var menuId = evnt.target.id;
        if(menuId == "0") 
        {
            Communicate();
        }
        if(menuId == "1") 
        {
            SendPostMessage();
        }       
        window.close();
    }
    catch(err)
    {
    }
}
function LinguifyOnClick()
{
    try
    {
        //var BodyTag = document.getElementsByTagName("body");
        var DefaultTag = document.getElementById("DefaultUl");
        for (iCtr = 0; iCtr<3; iCtr++)
        {
            var tmpTag = document.createElement("li");
            tmpTag.id = iCtr.toString();
            tmpTag.className = iCtr.toString();
            if(iCtr==0)
            {
                tmpTag.innerHTML = "   ConnectToNativeHost";
            }
            else if(iCtr==1)
            {
                tmpTag.innerHTML = "   SendPostMessage";
            }           
            DefaultTag.appendChild(tmpTag);
            tmpTag.addEventListener('click', MenuButtonClicked);
        }
    }   
    catch(err)
    {
    }
}
function SendPostMessage()
{
    var message = {"text" : "PostMessageSent_EXT"};
    alert("SendPostMessage=" + port + JSON.stringify(message));
    port.postMessage(message);
    alert("SendPostMessage=" + JSON.stringify(message));
}
function Communicate()
{
    port = chrome.runtime.connectNative('com.ln');
    //port = chrome.extension.connectNative('com.ln');
    port.onMessage.addListener(function(msg) 
    {
        alert("Received from native app:1 =" + msg);
    });
    port.onDisconnect.addListener(function() 
    {
        alert("Disconnected");
    });
}

app.exe(c# code)

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace sign
{
    class Program
    {
        public static void Main(string[] args)
        {
            JObject data;
            while ((data = Read()) != null)
            {
                var processed = ProcessMessage(data);
                Write(processed);
                if (processed == "exit")
                {
                    return;
                }
            }
        }       
        public static string ProcessMessage(JObject data)
        {
            try
            {
                var message = data["message"].Value<string>();
                switch (message)
                {
                    case "test":
                        return "testing!";
                    case "exit":
                        return "exit";
                    default:
                        return "echo: " + message;
                }
            }
            catch (Exception ex)
            {
                Console.Write("ProcessMessage =" + ex.Message);
            }
            return " ";
        }
        public static JObject Read()
        {
            try
            {
                var stdin = Console.OpenStandardInput();
                var length = 0;
                var lengthBytes = new byte[4];
                stdin.Read(lengthBytes, 0, 4);
                length = BitConverter.ToInt32(lengthBytes, 0);
                var buffer = new char[length];
                using (var reader = new StreamReader(stdin))
                {
                    while (reader.Peek() >= 0)
                    {
                        reader.Read(buffer, 0, buffer.Length);
                    }
                }
                return (JObject)JsonConvert.DeserializeObject<JObject>(new string(buffer));
            }
            catch (Exception ex)
            {
                Console.Write("Read =" + ex.Message);
            }
            return null;
        }
        public static void Write(JToken data)
        {
            try
            {
                var json = new JObject();
                json["data"] = data;
                var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToString(Formatting.None));
                var stdout = Console.OpenStandardOutput();
                stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
                stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
                stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
                stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
                stdout.Write(bytes, 0, bytes.Length);
                stdout.Flush();
            }
            catch (Exception ex)
            {
                Console.Write("Write =" + ex.Message);
            }
        }
    }
}

Upvotes: 0

Views: 801

Answers (1)

Ameet M.
Ameet M.

Reputation: 11

I am able to communicate now. What I changed is

  1. Created windows form app as native app, previously it was console app. Don't know why but extension could not communicate with console app.
    1. Instead of running .bat from json run direct native app.

Upvotes: 1

Related Questions