Search code examples
javascriptpythongoogle-chrome-extensionchrome-native-messaging

How to close chrome native app made with python?


I have made an chrome extension that interacts with a native app made with python. On closing my browser my native app doesn't end. I read somewhere that chrome sends -1 as message before ending. Following is the code I used to receive from extension -

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

def func():
    while True:
        if sys.stdin.read(1) == -1:
            logging.info("inside func got minus one")
            sys.exit()

p = multiprocessing.Process(target=func)
p.start()

Solution

  • You should have a look at https://developer.chrome.com/apps/nativeMessaging, which includes an example in Python. You need to read the length of the message. It is a 4 bytes (32 bit) integer. If the length is 0, that is your signal to exit.

    def func():
        while True:
            text_length_bytes = sys.stdin.read(4)
            if len(text_length_bytes) == 0:
                sys.exit(0)
            # still here, read text_lenth_bytes from stdin