Home  >  Q&A  >  body text

How to run python script from HTML in google chrome?

I'm building a chrome extension and I want to run a python script from my PC by clicking a button in the extension (basically HTML). The python script uses selenium web-driver to scrape data from the website and store it in another log file.

P粉471207302P粉471207302351 days ago1004

reply all(1)I'll reply

  • P粉316110779

    P粉3161107792023-11-03 14:40:52

    You basically use nativeMessaging. It allows you to create a communication bridge between your extension and an external process (such as python).

    nativeMessaging works on your computer and communicates with the Chrome extension via stdin and stdout. For example:

    Using Python hosting

    This is how you write a nativeMessaging host in python, I've included the full example from the documentation but it's easier to understand with less code.

    host.py

    This is basically an echo server that respects standard input and standard output, ensuring it is sent as a binary stream.

    #!/usr/bin/env python
    
    import struct
    import sys
    import os, msvcrt
    
    # Set the I/O to O_BINARY to avoid modifications from input/output streams.
    msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    
    # Helper function that sends a message to the webapp.
    def send_message(message):
       # Write message size.
      sys.stdout.write(struct.pack('I', len(message)))
      # Write the message itself.
      sys.stdout.write(message)
      sys.stdout.flush()
    
    # Thread that reads messages from the webapp.
    def read_thread_func():
      message_number = 0
      while 1:
        # Read the message length (first 4 bytes).
        text_length_bytes = sys.stdin.read(4)
    
        if len(text_length_bytes) == 0:
          sys.exit(0)
    
        # Unpack message length as 4 byte integer.
        text_length = struct.unpack('i', text_length_bytes)[0]
    
        # Read the text (JSON object) of the message.
        text = sys.stdin.read(text_length).decode('utf-8')
    
        send_message('{"echo": %s}' % text)
    
    
    def Main():
        read_thread_func()
        sys.exit(0)
    
    if __name__ == '__main__':
      Main()

    Host.json

    This defines the communication python host, making sure the extension guid is your extension's guid.

    {
      "name": "com.google.chrome.example.echo",
      "description": "Chrome Native Messaging API Example Host",
      "path": "host.bat",
      "type": "stdio",
      "allowed_origins": [
        "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
      ]
    }

    Host.bat

    This will run the python executable.

    @echo off
    python "%~dp0/host.py" %*

    Install host.bat

    You run this once to register your host with the operating system.

    REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "%~dp0host.json" /f

    Chrome Extension

    manifest.json

    Add permissions for nativeMessing

    {
      "permissions": [
        "nativeMessaging"
      ]
    }

    Communication.js

    In order to connect to the python host, you need to do the following:

    const hostName = "com.google.chrome.example.echo";
    let port = chrome.runtime.connectNative(hostName);
    port.onMessage.addListener(onNativeMessage);
    port.onDisconnect.addListener(onDisconnected);

    To send a message to your python host, simply send a json object to the port.

    const message = {"text": "Hello World"};
    if (port) {
        port.postMessage(message);
    }

    To know the error when disconnecting:

    function onDisconnected() {
      port = null;
      console.error(`Failed to connect: "${chrome.runtime.lastError.message}"`);
    }

    This complete example is in the documentation, I just renamed some stuff for clarity, it works on Windows/Unix https://chromium.googlesource.com/chromium/src/ /master/chrome/ common/extensions/docs/examples/api/nativeMessaging< /a>

    reply
    0
  • Cancelreply