Как запустить скрипт Python из HTML в Google Chrome? - PullRequest
0 голосов
/ 29 ноября 2018

Я создаю расширение для Chrome и хочу запустить скрипт Python, который находится на моем ПК, по нажатию кнопки из расширения (в основном HTML).Скрипт python использует селен-драйвер для очистки данных с веб-сайта и сохранения их в другом файле журнала.

1 Ответ

0 голосов
/ 29 ноября 2018

Вы в основном используете nativeMessaging .Он позволяет вам создать коммуникационный мост между вашим расширением и внешним процессом (таким как python).

Способ работы nativeMessaging заключается в установке host на вашеми связывается с расширением Chrome через стандартный ввод и стандартный вывод.Например:

Хост в Python

Вот как вы пишете свой nativeMessaging хост в Python. Я включил полный пример этого из документации, но сделал этолегче понять с меньшим количеством кода.

host.py

Это в основном эхо-сервер, учитывает stdin и stdout, обеспечивает его отправку в виде двоичного потока.

#!/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

Это определяет хост Python связи, убедитесь, что guid расширения является 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

Это работаетисполняемый файл python.

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

install_host.bat

Вы запускаете его один раз, чтобы зарегистрировать свой хост в своей ОС.

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

Расширение Chrome

manifest.json

Добавьте разрешения для nativeMessing

{
  "permissions": [
    "nativeMessaging"
  ]
}

communication.js

Чтобы подключиться к хосту python, вам нужно сделать следующее:

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

Чтобы отправить сообщение на хост python, просто отправьте объект json на порт.

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

Чтобы узнать об ошибке при отключении:

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

Этот полный пример приведен в документации, я просто переименовал некоторые вещи для ясности, доступные для Windows / Unix https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...