Chrome扩展Native Messaging无通信问题求助
问题:Chrome扩展与Python Native Messaging通信失败
尝试搭建Chrome扩展与Python外部脚本的Native Messaging通信,目标是将当前页面URL发送至Python脚本处理并返回数据,但始终无法正常工作。当前问题:
- 重载扩展时,VS Code窗口弹出并打开host.py文件,但并未运行该脚本
- 连接已建立(关闭VS Code窗口时,background.js的onDisconnect处理器会在浏览器控制台输出日志),但port.postMessage()无效果,无法确认Python脚本是否接收到数据
相关代码文件
host.json
{ "name": "com.google.chrome.noodleextension", "description": "chrome extension to display your favourite noodle", "path": "host.py", "type": "stdio", "allowed_origins": [ "chrome-extension://ffnijbdimnceklfeaihfedaiouygfdxe/" ] }
host.bat
@echo off C:\Python311\python.exe host.py
host.py
import sys import json import struct import os, msvcrt msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) def getMessage(): # 代码意外停在此处 rawLength = sys.stdin.buffer.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] message = sys.stdin.buffer.read(messageLength).decode('utf-8') return json.loads(message) def encodeMessage(messageContent): encodedContent = json.dumps(messageContent, separators=(',', ':')).encode('utf-8') encodedLength = struct.pack('@I', len(encodedContent)) return {'length': encodedLength, 'content': encodedContent} def sendMessage(encodedMessage): sys.stdout.buffer.write(encodedMessage['length']) sys.stdout.buffer.write(encodedMessage['content']) sys.stdout.buffer.flush() while True: receivedMessage = getMessage() sendMessage(encodeMessage("pong"))
background.js
const hostName = "com.google.chrome.noodleextension"; let port = chrome.runtime.connectNative(hostName); port.onMessage.addListener(function(text){ console.log("received", + text); }); port.onDisconnect.addListener(function(){ // 关闭VS Code窗口时会触发此日志,说明连接已建立 console.error(`Failed to connect: "${chrome.runtime.lastError.message}"`) }); const message = {text: "ping"}; port.postMessage(message);
解决方向
- 修正host.json的path配置:Windows下直接指定
host.py会用默认编辑器打开,而非运行脚本。需将path改为host.bat,通过批处理调用Python解释器执行脚本。 - 验证Python路径:确保host.bat中的
C:\Python311\python.exe路径正确,若Python已加入系统环境变量,可简化为python.exe避免路径错误。 - 添加调试输出:在Python脚本中使用
sys.stderr输出调试信息(如print("正在等待消息...", file=sys.stderr)),stdout需保留给Native Messaging通信,这样能在控制台查看脚本是否正常运行。 - 检查注册表配置:确认Native Messaging Host的注册表项(
HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.noodleextension)指向正确的host.json路径,路径需使用双反斜杠或正斜杠。 - 确认扩展ID匹配:检查host.json中
allowed_origins的扩展ID与Chrome扩展管理页面(开启开发者模式后可见)的实际ID完全一致。 - 验证stdin/stdout模式:确保msvcrt.setmode正确设置了二进制模式,避免Windows下换行符转换导致的通信数据异常。
内容的提问来源于stack exchange,提问作者yabadaba
相关产品推荐
相关产品推荐

