javascript 如何在谷歌Chrome中从HTML运行Python脚本?

5sxhfpxr  于 5个月前  发布在  Java
关注(0)|答案(2)|浏览(63)

我正在构建一个Chrome扩展程序,我想运行一个Python脚本,该脚本在我的PC上单击扩展程序的按钮(基本上是HTML)。Python脚本使用 selenium 网络驱动程序从网站上抓取数据并将其存储在另一个日志文件中。

qqrboqgw

qqrboqgw1#

你基本上使用nativeMessaging,它允许你在你的扩展和外部进程(比如python)之间建立一个通信桥梁。
nativeMessaging的工作方式是在您的机器上安装一个 host,并通过stdin和stdout与Chrome扩展程序进行通信。例如:

Python中的Host

这就是如何用python编写nativeMessaging主机,我已经从文档中包含了完整的示例,但是用更少的代码更容易理解。
host.py
这基本上是一个echo服务器,尊重标准输入和标准输出,确保它作为二进制流发送。

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

w6lpcovy

w6lpcovy2#

另一个不使用nativeMessaging的选项是使用pyodidepyscript

吡啶:

安装:
npm i pyodide
进口:

const { loadPyodide } = require("pyodide");

字符串
用途:

async function main() {
  let pyodide = await loadPyodide();
  // Pyodide is now ready to use...
  console.log(pyodide.runPython(`
    import sys
    sys.version
  `));
};
main();

相关问题