GoogleChrome / chrome-extensions-samples

Chrome Extensions Samples
https://developer.chrome.com/docs/extensions
Apache License 2.0
15.46k stars 8.23k forks source link

Error when communicating with the native messaging host. #607

Closed Scharfsinnig closed 3 years ago

Scharfsinnig commented 3 years ago

I'm confused by this error. I have already checked my manifest and reg settings. However, the error was still occurred.

image image image

# crx_python.py
"""
chrome extension messaging with local application.
"""
import sys
import struct
import json
import logging
from queue import Queue
import threading
import time

def read_message(queue):
    ctl = CrxToLocal()

    while True:
        ctl.set_message()
        ctl.send_message()
        print(">>>>> 发送信息......")
        logging.info(">>>>> 正在发送信息......")

        # print(">>>>> 正在接收数据......")
        # logging.info(">>>>> 正在接收数据......")
        # ctl.read_message()

        # ctl.handle_message()
        # logging.info(">>>>> 正在处理数据......")
        # print(">>>>> 正在处理数据......")
        time.sleep(3)

def main():
    # 主函数入口
    print(">>>>>>>>>>>>> starting......")
    # 1.对windows平台的行结束符处理:\r\n--->\n
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

    # 2.日志文件处理对象
    logging.basicConfig(
        filename="ctl.log",
        level=logging.INFO,
        format="%(levelname)s::%(asctime)s-%(module)s-%(lineno)d: %(message)s",
        datefmt="%Y-%d-%m %H:%M:%S")

    # 3.与chrome extension进行通信
    try:
        queue = Queue()
        threading.Thread()
        thread = threading.Thread(target=read_message, args=(queue,))
        thread.daemon = False
        thread.start()
    except Exception as e:
        logging.error(e)
        print(e)

# Chrome extension to local application:与chrome-extension进行通信的class
class CrxToLocal(object):
    def __init__(self):
        self._input_body = None
        self._output_body = None

    def read_message(self):
        # 读取标准输入流中的msg-header(first 4 bytes).
        text_length_bytes = sys.stdin.buffer.read(4)

        # Unpack message length as 4 byte integer, tuple = struct.unpack(fmt, buffer).
        text_length = struct.unpack("I", text_length_bytes)[0]

        # 读取标准输入流中的msg-body bytes
        self._input_body = sys.stdin.buffer.read(text_length)

    def set_message(self):
        self._output_body = "rpa,rpa,rpa".encode("utf-8")

    def handle_message(self):
        """更多处理对输入输出数据的操作..."""

        # 将chrome extension发送过来的数据保存到本地
        print(">>>>> get from big man:> {}".format(self._input_body))
        with open("./local_file.json", "a", encoding="utf-8") as f:
            json.dump(json.loads(self._input_body, encoding="utf-8"), f, ensure_ascii=False, indent=2)

        # _output_body的数据格式要求为JSON utf-8 bytes
        self._output_body = json.dumps({"response": "Nice to meet you."}).encode("utf-8")

    def send_message(self):
        # 将msg-header写到标准输出流, I表示int类型占4个字节,相关内容查看文档介绍python-doc/library/struct
        sys.stdout.buffer.write(struct.pack("I", len(self._output_body)))
        # 将msg-body写到标准输出流
        sys.stdout.buffer.write(self._output_body)
        sys.stdout.flush()

if __name__ == "__main__":
    main()
guest271314 commented 3 years ago

The issue appears to be on the Python script side.

guest271314 commented 3 years ago

Is the Python file set as executable?

Scharfsinnig commented 3 years ago

Is the Python file set as executable?

yes

guest271314 commented 3 years ago

Does ./local_file.json exist?

guest271314 commented 3 years ago

According to https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging -u flag is necessary for Python on Windows.

dotproto commented 3 years ago

Closing this issue as it is not a bug or feature request for the chrome-extension-samples repository. I don't mind if you two continue to try to work through the problem, but @Scharfsinnig, I'd encourage you to post future questions on the chromium-extensions Google Group or on StackOverflow.