You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell作为Chrome原生消息主机?协议实现报错求助

排查Chrome原生消息主机发送消息失败的问题

核心问题分析

你遇到的「Error when communicating with the native messaging host」错误,根源是标准输出被额外内容污染,导致输出格式不符合原生消息协议要求——Chrome仅接受严格的「32位原生字节序长度前缀 + UTF-8编码JSON」结构,任何多余输出都会破坏解析逻辑。

1. PowerShell脚本的多余输出

你的native-messaging-example-host.ps1中存在单独的$Writer行,这会将BinaryWriter对象的字符串标识(如System.IO.BinaryWriter)输出到标准输出,直接打乱了原生消息的格式结构。

2. 批处理脚本的多余输出

MyExample1.bat里的echo.、echo Waiting seconds命令,即使开启@echo off,仍会向标准输出写入空行和文本,同样会污染原生消息的纯净输出流。

3. 潜在的文件编码问题

Get-Content未指定编码时,会使用系统默认编码读取test.txt,若文件不是UTF-8格式,可能导致ConvertFrom-Json解析失败,间接影响后续消息生成。


修复后的代码

修正后的PowerShell脚本(native-messaging-example-host.ps1)

$file = "D:\temp\test\test.txt"
# 明确指定UTF-8编码读取文件,避免JSON解析异常
$data = Get-Content $file -Raw -Encoding UTF8
$Objectdata = $data | ConvertFrom-Json
$formatedData = $Objectdata | Select-Object -Property message | ConvertTo-Json -Depth 1 -Compress
$encData = [System.Text.UTF8Encoding]::UTF8.GetBytes($formatedData)

$stdOut = [System.Console]::OpenStandardOutput()
$writer = New-Object System.IO.BinaryWriter($stdOut)
# 写入32位原生字节序的消息长度(Windows默认小端字节序符合协议要求)
$writer.Write([Int32]$encData.Length)
# 写入UTF-8编码的JSON消息体
$writer.Write($encData)
# 确保数据全部输出并释放资源
$writer.Flush()
$writer.Close()
$stdOut.Close()
  • 移除了会产生多余输出的$Writer行
  • 明确指定文件读取编码为UTF8,避免JSON解析错误
  • 规范了资源释放逻辑,确保输出流正确关闭

修正后的批处理脚本(MyExample1.bat)

@echo off
# 完全移除所有额外输出命令,仅执行PowerShell脚本
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "D:\projects-repo\CromeNativeMessaging\NativeHost\native-messaging-example-host.ps1"
  • 删除了color 1F、echo.、timeout等所有会产生额外输出的命令
  • 确保批处理仅传递PowerShell脚本的纯净输出给Chrome

验证JSON配置文件(NativeMessageHello.json)

你的配置文件格式正确,只需确认path字段指向修正后的批处理脚本即可,路径使用正斜杠或转义反斜杠均有效。


额外验证步骤

  1. 手动运行PowerShell脚本,通过.\native-messaging-example-host.ps1 | Format-Hex查看输出:开头4字节应为消息长度的二进制值,后续为UTF-8编码的JSON内容
  2. 确保test.txt中的内容是合法JSON,例如:
    {"message": "Hello from file"}
    
  3. 检查Chrome扩展的manifest.json是否包含"nativeMessaging"权限,且allowed_origins中的扩展ID与实际完全匹配

内容的提问来源于stack exchange,提问作者user3571552

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:35:21