Chrome Native Messaging API是如何实现跨平台通信的?

Chrome Native Messaging API 允许 Chrome 与本地原生应用程序进行通信,通过标准输入/输出流传输消息。

Chrome Native Messaging API是一种允许网页通过浏览器扩展与本地应用程序进行通信的技术,以下是关于Chrome Native Messaging API的详细介绍:

Chrome Native Messaging API是如何实现跨平台通信的?

一、

在Chrome浏览器中,Native Messaging是唯一能让web页面调用Native API的技术,它实现了web页面、浏览器扩展和本地消息主机之间的JSON通讯,这种通信方式通过标准输入和标准输出流进行,使用UTF-8编码的JSON字符串。

二、Native Messaging Host

1. 功能

native messaging host从stdin读取消息,从stdout返回消息,stderr用于返回错误消息给chrome。

一次最多能向native messaging host发送4GB字节的请求,native messaging host一次最多能返回1M字节的消息。

2. 实现

native messaging host通常由C++源文件和manifest文件两部分组成。

在Windows系统中,可以使用VisualStudio创建chrome_native_messaging_host win32 console project,并加入相关文件进行编译。

3. manifest文件

Chrome Native Messaging API是如何实现跨平台通信的?

manifest文件定义了native messaging host的配置,包括名称、描述、路径、类型和允许的来源。

例如

{
  "name": "com.my_company.my_application",
  "description": "我的应用程序",
  "path": "C:\\Program Files\\My Application\\chrome_native_messaging_host.exe",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
  ]
}

manifest文件的位置取决于操作系统Windows系统可以放在相对于清单文件所在目录的路径,Linux和OSX系统必须使用绝对路径。

三、Extension部分

1. 连接与通信

扩展程序使用chrome.runtime.connectNativechrome.runtime.sendNativeMessage与native messaging host进行通信。

当使用chrome.runtime.connectNative时,Chrome浏览器会启动native messaging host进程,并保持其运行状态直到端口释放。

当使用chrome.runtime.sendNativeMessage时,Chrome浏览器会为每条消息创建一个新的native messaging host进程。

2. 权限配置

扩展清单文件必须包含nativeMessaging,tabs,http://*/,https://*/等权限。

Chrome Native Messaging API是如何实现跨平台通信的?

四、Web Page部分

1. 事件发布

前端页面通过JavaScript发布事件,使Chrome扩展程序在接收到事件时调用本地应用程序。

五、问题与解答

Q1: Chrome Native Messaging Host的manifest文件中,"allowed_origins"字段的作用是什么?

A1: "allowed_origins"字段指定了哪些扩展程序可以访问native messaging host,这是一个安全措施,确保只有授权的扩展程序能够与之通信。

Q2: 如果Chrome Native Messaging Host进程意外退出,会发生什么?

A2: 如果native messaging host进程意外退出,Chrome浏览器会记录一个错误,并且任何通过该进程进行的通信都将失败,开发者需要在代码中处理这种情况,例如通过重试机制或用户提示来恢复通信。

Chrome Native Messaging API提供了一种强大的机制,使得web页面能够通过浏览器扩展与本地应用程序进行安全的通信,这在需要调用本地API或执行复杂本地操作时非常有用。

小伙伴们,上文介绍了“chrome native message api”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/43725.html<

(0)
运维的头像运维
上一篇2025-01-01 18:55
下一篇 2025-01-01 18:59

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注