From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../api/runtime/connectnative/index.html | 114 +++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 files/zh-cn/mozilla/add-ons/webextensions/api/runtime/connectnative/index.html (limited to 'files/zh-cn/mozilla/add-ons/webextensions/api/runtime/connectnative/index.html') diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/connectnative/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/connectnative/index.html new file mode 100644 index 0000000000..d3d4d9a14d --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/connectnative/index.html @@ -0,0 +1,114 @@ +--- +title: 连接本地应用程序方法 - runtime.connectNative() +slug: Mozilla/Add-ons/WebExtensions/API/runtime/connectNative +tags: + - 附加组件连接本地应用程序 +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/connectNative +--- +
{{AddonSidebar()}}
+ +
该方法能够把附加组件和用户计算机上的一个本地应用程序相连接.
+ +
 
+ +
同时我们需要本地应用程序的名称作为参数. 当启动本地应用程序的时候会返回一个{{WebExtAPIRef("runtime.Port")}} 对象给调用者.
+ +
 
+ +
之后可以通过该对象的 Port.onMessage() 和 Port.postMessage()方法来和本地应用程序进行信息交互.
+ +
 
+ +
本地应用程序会一直运行直到退出, 除非调用了 Port.disconnect()方法, 亦或创建该Port对象的页面被摧毁了. 一旦Port对象断开连接, 浏览器会给该进程几秒的时间以便安全优雅的退出和释放, 之后如果发现该进程没退出的话就直接暴力干掉.
+ +
 
+ +

更多信息, 请查看 Native messaging.

+ +

语法

+ +
var port = browser.runtime.connectNative(
+  application // 这是一个字符串
+)
+
+ +

参数

+ +
+
application
+
值类型为string. 该参数的值为要连接的本地应用程序的名称. 必须要跟 native application's manifest file 中的"name"特性的值一致.
+
+ +

返回值

+ +

是一个 {{WebExtAPIRef('runtime.Port')}} 对象. 该对象是用来跟本地应用程序进行消息交互的.

+ +

浏览器的兼容性

+ + + +

{{Compat("webextensions.api.runtime.connectNative")}}

+ +

示例

+ +

本示例中连接了本地应用程序"ping_pong"并且启动了监听以便接收消息. 当用户单击浏览器上的操作按钮时它会发送一个本地应用程序的消息:

+ +
/*
+启动时, 连接"ping_pong"本地应用程序.
+*/
+var port = browser.runtime.connectNative("ping_pong");
+
+/*
+监听(接收)来自"ping_pong"本地应用程序的消息.
+*/
+port.onMessage.addListener((response) => {
+  console.log("Received: " + response);
+});
+
+/*
+当浏览器上的单击操作被触发时, 发送一个消息给本地应用程序.
+*/
+browser.browserAction.onClicked.addListener(() => {
+  console.log("Sending:  ping");
+  port.postMessage("ping");
+});
+ +

{{WebExtExamples}}

+ +
万分感谢 + +

该 API 是基于 Chromium 的 chrome.runtime API. 本文档采自 Chromium 代码中的 runtime.json.

+ +

Microsoft Edge 的兼容性数据由微软公司提供, 并被列入以下许可证 Creative Commons Attribution 3.0 United States License.

+
+ + -- cgit v1.2.3-54-g00ecf