Search code examples
cgoogle-chromenativemessaging

Chrome extension communication with C native app


I am trying to send a string from my C native app to my chrome extension using the Native Messages API. However I am not being able to receive it on the extension.

The extension behavior is very simple, when i click on the extension icon I want to receive my C program string on the browser console, But I receive the following:

Received[object Object]                    background.js:7 
Disconnected                               _generated_background_page.html:1 
Unchecked runtime.lastError: Native host has exited.

C app manifest:

{
  "name": "com.wasm.test",
  "description": "My Application",
  "path": "/home/chrome-native-message-test/app",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://oegageepidiekaeopfojnglhkmdjaomi/"
  ]
}

C app:

 #include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
    // Define our message
    char message[] = "{\"text\": \"This is a response message\"}";
    // Collect the length of the message
    unsigned int len = strlen(message);
    // We need to send the 4 bytes of length information
    printf("%c%c%c%c", (char) (len & 0xff),
                       (char) ((len>>8) & 0xFF),
                       (char) ((len>>16) & 0xFF),
                       (char) ((len>>24) & 0xFF));
    // Now we can output our message
    printf("%s", message);
    return 0;
}

extension manifest:

{
    "name": "extension test",
    "version": "1.0",
    "description": "native message testing",
    "permissions": ["nativeMessaging"],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_title": "receive native message",
    },
    "manifest_version": 2
}

extension background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    var port = chrome.runtime.connectNative('com.wasm.test');
    port.onMessage.addListener(function(msg) {
        console.log("Received" + msg);
    });
    port.onDisconnect.addListener(function() {
        console.log("Disconnected");
    });
});

Am I missing something? Thanks


Solution

  • It is working. I was trying to print the RAW json..

    Use console.log(JSON.stringify(result)) to get the JSON in a string format.