Native messaging not working from host to chrome extension

653 Views Asked by At

I am working on a chrome extension native messaging with the host on Python. The communication from extension to python works perfectly fine. But when I am trying to send the message from the host to the extension, it is not working. I am getting no errors. Even I have enabled logging for the browser. I have tested on Linux and Mac with the same issue. Below is my code. Any help would be appreciated.

background.js

const port = chrome.runtime.connectNative("com.google.chrome.uniphore");
port.onDisconnect.addListener((p) => console.log(chrome.runtime.lastError));

port.postMessage("ping")

port.onMessage.addListener(function (msg) {
  console.log('Received' + msg);
  return false;
});

chrome.runtime.onInstalled.addListener((reason) => {
  console.log(reason);
});

main.py

import sys
import json
import struct



def getMessage():
    try:
        rawLength = sys.stdin.buffer.read(4)
        if len(rawLength) == 0:
            sys.exit(0)
        messageLength = struct.unpack('@I', rawLength)[0]
        message = sys.stdin.buffer.read(messageLength).decode('utf-8')
        return json.loads(message)
    except Exception as x:
        print("Error", x)

# Send an encoded message to stdout
def sendMessage(encodedMessage):
    try:
        sys.stdout.buffer.write(encodedMessage["length"])
        sys.stdout.buffer.write(encodedMessage["content"])
        sys.stdout.flush()
    except Exception as x:
        print("Error", x)

def encodeMessage(messageContent):
    # https://docs.python.org/3/library/json.html#basic-usage
    # To get the most compact JSON representation, you should specify 
    # (',', ':') to eliminate whitespace.
    # We want the most compact representation because the browser rejects
    # messages that exceed 1 MB.
    encoded_content = json.dumps(messageContent).encode("utf-8")
    encoded_length = struct.pack("@I", len(encoded_content))
    return {"length": encoded_length, "content": encoded_content}

while True:
    receivedMessage = getMessage()
    if receivedMessage == "ping":
        sendMessage(encodeMessage("pong"))

run.sh

#!/bin/sh
python3 main.py >> hello 2>> err_file

com.google.chrome.echo.json

{
    "name": "com.google.chrome.echo",
    "description": "echo Application",
    "path": "/Applications/native/run.sh",
    "type": "stdio",
    "allowed_origins": [
      "chrome-extension://bmfbcejdknlknpncfpeloejonjoledha/"
    ]
}
0

There are 0 best solutions below