diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
commit | 33058f2b292b3a581333bdfb21b8f671898c5060 (patch) | |
tree | 51c3e392513ec574331b2d3f85c394445ea803c6 /files/zh-cn/mozilla/add-ons/webextensions/api/runtime | |
parent | 8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff) | |
download | translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2 translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip |
initial commit
Diffstat (limited to 'files/zh-cn/mozilla/add-ons/webextensions/api/runtime')
10 files changed, 1413 insertions, 0 deletions
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 +--- +<div>{{AddonSidebar()}}</div> + +<div>该方法能够把附加组件和用户计算机上的一个本地应用程序相连接.</div> + +<div> </div> + +<div>同时我们需要本地应用程序的名称作为参数. 当启动本地应用程序的时候会返回一个{{WebExtAPIRef("runtime.Port")}} 对象给调用者.</div> + +<div> </div> + +<div>之后可以通过该对象的 Port.onMessage() 和 Port.postMessage()方法来和本地应用程序进行信息交互.</div> + +<div> </div> + +<div>本地应用程序会一直运行直到退出, 除非调用了 <code>Port.disconnect()</code>方法, 亦或创建该Port对象的页面被摧毁了. 一旦Port对象断开连接, 浏览器会给该进程几秒的时间以便安全优雅的退出和释放, 之后如果发现该进程没退出的话就直接暴力干掉.</div> + +<div> </div> + +<p>更多信息, 请查看 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging">Native messaging</a>.</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox brush:js">var port = browser.runtime.connectNative( + application // 这是一个字符串 +) +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>application</code></dt> + <dd><code>值类型为string</code>. 该参数的值为要连接的本地应用程序的名称. 必须要跟 <a href="/en-US/Add-ons/WebExtensions/Native_messaging#App_manifest">native application's manifest file</a> 中的"name"特性的值一致.</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>是一个 {{WebExtAPIRef('runtime.Port')}} 对象. 该对象是用来跟本地应用程序进行消息交互的.</p> + +<h2 id="浏览器的兼容性">浏览器的兼容性</h2> + +<p class="hidden">本页中的兼容性表格是通过结构化后的数据生成的. 如果你想提供更多的兼容性数据, 请检出 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 添加修改后再给我们发送一个pull请求.</p> + +<p>{{Compat("webextensions.api.runtime.connectNative")}}</p> + +<h2 id="示例">示例</h2> + +<p>本示例中连接了本地应用程序"ping_pong"并且启动了监听以便接收消息. 当用户单击浏览器上的操作按钮时它会发送一个本地应用程序的消息:</p> + +<pre class="brush: js">/* +启动时, 连接"ping_pong"本地应用程序. +*/ +var port = <code class="language-js">browser</code>.runtime.connectNative("ping_pong"); + +/* +监听(接收)来自"ping_pong"本地应用程序的消息. +*/ +port.onMessage.addListener((response) => { + console.log("Received: " + response); +}); + +/* +当浏览器上的单击操作被触发时, 发送一个消息给本地应用程序. +*/ +<code class="language-js">browser</code>.browserAction.onClicked.addListener(() => { + console.log("Sending: ping"); + port.postMessage("ping"); +});</pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>万分感谢</strong> + +<p>该 API 是基于 Chromium 的 <a href="https://developer.chrome.com/extensions/runtime#method-connectNative"><code>chrome.runtime</code></a> API. 本文档采自 Chromium 代码中的 <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a>.</p> + +<p>Microsoft Edge 的兼容性数据由微软公司提供, 并被列入以下许可证 Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html new file mode 100644 index 0000000000..77870d7010 --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html @@ -0,0 +1,79 @@ +--- +title: 读取主文件信息方法 - runtime.getManifest() +slug: Mozilla/Add-ons/WebExtensions/API/runtime/getManifest +tags: + - 读取主文件信息方法 + - 附加组件 +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/getManifest +--- +<div>{{AddonSidebar()}}</div> + +<div>该方法会获取一个完整的主文件 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json </a>, 并返回一个序列化后的 JSON 对象.</div> + +<div> </div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox brush:js">browser.runtime.getManifest() +</pre> + +<h3 id="参数">参数</h3> + +<p>无.</p> + +<h3 id="返回值">返回值</h3> + +<p>是一个能表示主文件所有信息的 JSON 对象.</p> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.getManifest")}}</p> + +<h2 id="示例">示例</h2> + +<p>取得主文件中的 name 特性的值, 并输出到控制台:</p> + +<pre class="brush: js">var manifest = browser.runtime.getManifest(); +console.log(manifest.name);</pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#method-getManifest"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/index.html new file mode 100644 index 0000000000..5a1618e9e7 --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/index.html @@ -0,0 +1,181 @@ +--- +title: runtime +slug: Mozilla/Add-ons/WebExtensions/API/runtime +tags: + - API + - Add-ons + - Extensions + - Interface + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebExtensions + - runtime +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime +--- +<div>{{AddonSidebar}}</div> + +<p>该模块提供关于附加组件以及运行环境的信息。</p> + +<p>它提供一组消息通信API,允许你:</p> + +<ul> + <li>在附加组件的不同模块间通信。</li> + <li>和其它的附加组件通信。</li> + <li>和native应用通信。</li> +</ul> + +<h2 id="Types">Types</h2> + +<dl> + <dt>{{WebExtAPIRef("runtime.Port")}}</dt> + <dd>表示两个特定上下文之间的连接的一端,可用于交换消息。</dd> + <dt>{{WebExtAPIRef("runtime.MessageSender")}}</dt> + <dd> + <div class="trans-right"> + <div class="output-wrap small-font"> + <div class="output-mod ordinary-wrap"> + <div class="output-bd" dir="ltr" style="padding-bottom: 0px;"> + <p class="ordinary-output target-output clearfix"><span>包含有关消息或连接请求的发件人的信息。</span></p> + </div> + </div> + </div> + </div> + </dd> + <dt>{{WebExtAPIRef("runtime.PlatformOs")}}</dt> + <dd>标识浏览器的操作系统。</dd> + <dt>{{WebExtAPIRef("runtime.PlatformArch")}}</dt> + <dd>标识浏览器的处理器架构。</dd> + <dt>{{WebExtAPIRef("runtime.PlatformInfo")}}</dt> + <dd>包含有关浏览器正在运行的平台的信息。</dd> + <dt>{{WebExtAPIRef("runtime.RequestUpdateCheckStatus")}}</dt> + <dd>{{WebExtAPIRef("runtime.requestUpdateCheck()")}} 的返回结果。</dd> + <dt>{{WebExtAPIRef("runtime.OnInstalledReason")}}</dt> + <dd>{{WebExtAPIRef("runtime.onInstalled")}} 事件被触发的原因。</dd> + <dt>{{WebExtAPIRef("runtime.OnRestartRequiredReason")}}</dt> + <dd>{{WebExtAPIRef("runtime.onRestartRequired")}} 事件被触发的原因。</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{WebExtAPIRef("runtime.lastError")}}</dt> + <dd>当异步方法执行时发生了错误,它需要向其调用方报告时,该值会被设置。</dd> + <dt>{{WebExtAPIRef("runtime.id")}}</dt> + <dd>当前扩展的ID。</dd> +</dl> + +<h2 id="Functions">Functions</h2> + +<dl> + <dt>{{WebExtAPIRef("runtime.getBackgroundPage()")}}</dt> + <dd>取得当前扩展的后台页的 <a href="https://wiki.developer.mozilla.org/zh-CN/docs/Web/API/Window">Window</a> 对象。</dd> + <dt>{{WebExtAPIRef("runtime.openOptionsPage()")}}</dt> + <dd> + <p>打开你的扩展的 <a href="/zh-CN/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Options_pages">选项页面</a>。</p> + </dd> + <dt>{{WebExtAPIRef("runtime.getManifest()")}}</dt> + <dd>获得完整的 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a> 声明文件的序列化对象。</dd> + <dt>{{WebExtAPIRef("runtime.getURL()")}}</dt> + <dd>给定某个打包在扩展中的资源的基于 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a> 相对路径,返回一个完整有效的 URL。</dd> + <dt>{{WebExtAPIRef("runtime.setUninstallURL()")}}</dt> + <dd>指定一个此扩展被卸载后打开的 URL。</dd> + <dt>{{WebExtAPIRef("runtime.reload()")}}</dt> + <dd>重新加载此扩展。</dd> + <dt>{{WebExtAPIRef("runtime.requestUpdateCheck()")}}</dt> + <dd>检查此扩展的更新。</dd> + <dt>{{WebExtAPIRef("runtime.connect()")}}</dt> + <dd>建立一个页面脚本到扩展主进程,或扩展主进程到页面脚本之间的通信连接。</dd> + <dt>{{WebExtAPIRef("runtime.connectNative()")}}</dt> + <dd> + <div>建立一个浏览器扩展与用户电脑上的原生应用的通信连接。</div> + </dd> + <dt>{{WebExtAPIRef("runtime.sendMessage()")}}</dt> + <dd>发送一条消息到此扩展或其他扩展的事件监听器,类似于 {{WebExtAPIRef('runtime.connect')}} 但只能发送一条消息,以及可选的响应处理函数。</dd> + <dt>{{WebExtAPIRef("runtime.sendNativeMessage()")}}</dt> + <dd>从扩展发送一条消息到原生应用。</dd> + <dt>{{WebExtAPIRef("runtime.getPlatformInfo()")}}</dt> + <dd>返回当前所在平台的信息。</dd> + <dt>{{WebExtAPIRef("runtime.getBrowserInfo()")}}</dt> + <dd>返回此扩展所在的浏览器的信息。</dd> + <dt>{{WebExtAPIRef("runtime.getPackageDirectoryEntry()")}}</dt> + <dd>返回此扩展所在目录的 DirectoryEntry。</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt>{{WebExtAPIRef("runtime.onStartup")}}</dt> + <dd>当一个拥有此扩展的账户第一次启动时触发,注意若处于隐私模式中则不会触发。</dd> + <dt>{{WebExtAPIRef("runtime.onInstalled")}}</dt> + <dd>当扩展第一次安装,扩展更新,浏览器更新后触发。</dd> + <dt>{{WebExtAPIRef("runtime.onSuspend")}}</dt> + <dd>当扩展将被停止前触发,使得扩展可以执行一些清理工作。</dd> + <dt>{{WebExtAPIRef("runtime.onSuspendCanceled")}}</dt> + <dd>在此事件 {{WebExtAPIRef("runtime.onSuspend")}} 后触发,表明扩展最终没有被停止。</dd> + <dt>{{WebExtAPIRef("runtime.onUpdateAvailable")}}</dt> + <dd>当扩展更新可用时触发,注意若扩展运行中,更新不会马上被安装。</dd> + <dt>{{WebExtAPIRef("runtime.onBrowserUpdateAvailable")}}</dt> + <dd>当浏览器更新可用时触发,注意浏览器需要重启才能安装更新。</dd> + <dt>{{WebExtAPIRef("runtime.onConnect")}}</dt> + <dd>与扩展进程或页面脚本(content script)建立通信连接时触发。</dd> + <dt>{{WebExtAPIRef("runtime.onConnectExternal")}}</dt> + <dd>与其他扩展建立通信连接时触发。</dd> + <dt>{{WebExtAPIRef("runtime.onMessage")}}</dt> + <dd>当收到扩展进程或页面脚本(content script)的消息时触发。</dd> + <dt>{{WebExtAPIRef("runtime.onMessageExternal")}}</dt> + <dd>当收到其他扩展的消息时触发,不能在页面脚本(content script)中使用。</dd> + <dt>{{WebExtAPIRef("runtime.onRestartRequired")}}</dt> + <dd>当设备要重启时触发。</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("webextensions.api.runtime")}}</p> + +<div class="hidden note"> +<p>The "Chrome incompatibilities" section is included from <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities"> https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a> using the <a href="/en-US/docs/Template:WebExtChromeCompat">WebExtChromeCompat</a> macro.</p> + +<p>If you need to update this content, edit <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities">https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a>, then shift-refresh this page to see your changes.</p> +</div> + +<p>{{Compat("webextensions.api.runtime")}} {{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre class="notranslate">// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/onconnect/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/onconnect/index.html new file mode 100644 index 0000000000..d51cb8abbc --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/onconnect/index.html @@ -0,0 +1,228 @@ +--- +title: runtime.onConnect +slug: Mozilla/Add-ons/WebExtensions/API/runtime/onConnect +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/onConnect +--- +<div>{{AddonSidebar()}}</div> + +<p>当使用扩展处理或content script建立连接时触发.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox brush:js">browser.runtime.onConnect.addListener(listener) +browser.runtime.onConnect.removeListener(listener) +browser.runtime.onConnect.hasListener(listener) +</pre> + +<p>事件有三个方法:</p> + +<dl> + <dt><code>addListener(callback)</code></dt> + <dd>为 这个事件添加一个监听器.</dd> + <dt><code>removeListener(listener)</code></dt> + <dd>停止监听这个事件. <code>listener</code> 参数就是要移除的监听器.</dd> + <dt><code>hasListener(listener)</code></dt> + <dd>检查监听器是否已经注册到这个事件上. 如果已经监听,则返回 <code>true</code> 否则返回 <code>false</code>.</dd> +</dl> + +<h2 id="addListener_语法">addListener 语法</h2> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>function</code></dt> + <dd> + <p>A callback function that will be called when this event occurs. The function will be passed the following arguments:</p> + + <dl class="reference-values"> + <dt><code>port</code></dt> + <dd>A {{WebExtAPIRef('runtime.Port')}} object connecting the current script to the other context it is connecting to.</dd> + </dl> + </dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.onConnect")}}</p> + +<h2 id="Examples">Examples</h2> + +<p>This content script:</p> + +<ul> + <li>connects to the background script, and stores the <code>Port</code> in a variable <code>myPort</code></li> + <li>listens for messages on <code>myPort</code>, and logs them</li> + <li>sends messages to the background script, using <code>myPort</code>, when the user clicks the document</li> +</ul> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// content-script.js</span> + +<span class="keyword token">var</span> myPort <span class="operator token">=</span> browser<span class="punctuation token">.</span>runtime<span class="punctuation token">.</span><span class="function token">connect</span><span class="punctuation token">(</span><span class="punctuation token">{</span>name<span class="punctuation token">:</span><span class="string token">"port-from-cs"</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +myPort<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">{</span>greeting<span class="punctuation token">:</span> <span class="string token">"hello from content script"</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +myPort<span class="punctuation token">.</span>onMessage<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span>m<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"In content script, received message from background script: "</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>m<span class="punctuation token">.</span>greeting<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +document<span class="punctuation token">.</span>body<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"click"</span><span class="punctuation token">,</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + myPort<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">{</span>greeting<span class="punctuation token">:</span> <span class="string token">"they clicked the page!"</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>The corresponding background script:</p> + +<ul> + <li>listens for connection attempts from the content script</li> + <li>when it receives a connection attempt: + <ul> + <li>stores the port in a variable named <code>portFromCS</code></li> + <li>sends the content script a message using the port</li> + <li>starts listening to messages received on the port, and logs them</li> + </ul> + </li> + <li>sends messages to the content script, using <code>portFromCS</code>, when the user clicks the extension's browser action</li> +</ul> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// background-script.js</span> + +<span class="keyword token">var</span> portFromCS<span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">connected</span><span class="punctuation token">(</span>p<span class="punctuation token">)</span> <span class="punctuation token">{</span> + portFromCS <span class="operator token">=</span> p<span class="punctuation token">;</span> + portFromCS<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">{</span>greeting<span class="punctuation token">:</span> <span class="string token">"hi there content script!"</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + portFromCS<span class="punctuation token">.</span>onMessage<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span>m<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"In background script, received message from content script"</span><span class="punctuation token">)</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>m<span class="punctuation token">.</span>greeting<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +browser<span class="punctuation token">.</span>runtime<span class="punctuation token">.</span>onConnect<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span>connected<span class="punctuation token">)</span><span class="punctuation token">;</span> + +browser<span class="punctuation token">.</span>browserAction<span class="punctuation token">.</span>onClicked<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + portFromCS<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">{</span>greeting<span class="punctuation token">:</span> <span class="string token">"they clicked the button!"</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#event-onConnect"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">检测语言</option><option value="eo">世界语</option><option value="zh-CN">中文简体</option><option value="zh-TW">中文繁体</option><option value="da">丹麦语</option><option value="uk">乌克兰语</option><option value="uz">乌兹别克语</option><option value="ur">乌尔都语</option><option value="hy">亚美尼亚语</option><option value="ig">伊博语</option><option value="ru">俄语</option><option value="bg">保加利亚语</option><option value="si">僧伽罗语</option><option value="hr">克罗地亚语</option><option value="is">冰岛语</option><option value="gl">加利西亚语</option><option value="ca">加泰罗尼亚语</option><option value="hu">匈牙利语</option><option value="zu">南非祖鲁语</option><option value="kn">卡纳达语</option><option value="hi">印地语</option><option value="su">印尼巽他语</option><option value="jw">印尼爪哇语</option><option value="id">印尼语</option><option value="gu">古吉拉特语</option><option value="kk">哈萨克语</option><option value="tr">土耳其语</option><option value="tg">塔吉克语</option><option value="sr">塞尔维亚语</option><option value="st">塞索托语</option><option value="cy">威尔士语</option><option value="bn">孟加拉语</option><option value="ceb">宿务语</option><option value="ne">尼泊尔语</option><option value="eu">巴斯克语</option><option value="af">布尔语(南非荷兰语)</option><option value="iw">希伯来语</option><option value="el">希腊语</option><option value="de">德语</option><option value="it">意大利语</option><option value="yi">意第绪语</option><option value="la">拉丁语</option><option value="lv">拉脱维亚语</option><option value="no">挪威语</option><option value="cs">捷克语</option><option value="sk">斯洛伐克语</option><option value="sl">斯洛文尼亚语</option><option value="sw">斯瓦希里语</option><option value="pa">旁遮普语</option><option value="ja">日语</option><option value="ka">格鲁吉亚语</option><option value="mi">毛利语</option><option value="fr">法语</option><option value="pl">波兰语</option><option value="bs">波斯尼亚语</option><option value="fa">波斯语</option><option value="te">泰卢固语</option><option value="ta">泰米尔语</option><option value="th">泰语</option><option value="ht">海地克里奥尔语</option><option value="ga">爱尔兰语</option><option value="et">爱沙尼亚语</option><option value="sv">瑞典语</option><option value="be">白俄罗斯语</option><option value="lt">立陶宛语</option><option value="so">索马里语</option><option value="yo">约鲁巴语</option><option value="my">缅甸语</option><option value="ro">罗马尼亚语</option><option value="lo">老挝语</option><option value="fi">芬兰语</option><option value="hmn">苗语</option><option value="en">英语</option><option value="nl">荷兰语</option><option value="tl">菲律宾语</option><option value="pt">葡萄牙语</option><option value="mn">蒙古语</option><option value="es">西班牙语</option><option value="ha">豪萨语</option><option value="vi">越南语</option><option value="az">阿塞拜疆语</option><option value="sq">阿尔巴尼亚语</option><option value="ar">阿拉伯语</option><option value="ko">韩语</option><option value="mk">马其顿语</option><option value="mg">马尔加什语</option><option value="mr">马拉地语</option><option value="ml">马拉雅拉姆语</option><option value="ms">马来语</option><option value="mt">马耳他语</option><option value="km">高棉语</option><option value="ny">齐切瓦语</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="切换语言"> </div> + </td> + <td class="SL_td"><select><option value="eo">世界语</option><option value="zh-CN">中文简体</option><option value="zh-TW">中文繁体</option><option value="da">丹麦语</option><option value="uk">乌克兰语</option><option value="uz">乌兹别克语</option><option value="ur">乌尔都语</option><option value="hy">亚美尼亚语</option><option value="ig">伊博语</option><option value="ru">俄语</option><option value="bg">保加利亚语</option><option value="si">僧伽罗语</option><option value="hr">克罗地亚语</option><option value="is">冰岛语</option><option value="gl">加利西亚语</option><option value="ca">加泰罗尼亚语</option><option value="hu">匈牙利语</option><option value="zu">南非祖鲁语</option><option value="kn">卡纳达语</option><option value="hi">印地语</option><option value="su">印尼巽他语</option><option value="jw">印尼爪哇语</option><option value="id">印尼语</option><option value="gu">古吉拉特语</option><option value="kk">哈萨克语</option><option value="tr">土耳其语</option><option value="tg">塔吉克语</option><option value="sr">塞尔维亚语</option><option value="st">塞索托语</option><option value="cy">威尔士语</option><option value="bn">孟加拉语</option><option value="ceb">宿务语</option><option value="ne">尼泊尔语</option><option value="eu">巴斯克语</option><option value="af">布尔语(南非荷兰语)</option><option value="iw">希伯来语</option><option value="el">希腊语</option><option value="de">德语</option><option value="it">意大利语</option><option value="yi">意第绪语</option><option value="la">拉丁语</option><option value="lv">拉脱维亚语</option><option value="no">挪威语</option><option value="cs">捷克语</option><option value="sk">斯洛伐克语</option><option value="sl">斯洛文尼亚语</option><option value="sw">斯瓦希里语</option><option value="pa">旁遮普语</option><option value="ja">日语</option><option value="ka">格鲁吉亚语</option><option value="mi">毛利语</option><option value="fr">法语</option><option value="pl">波兰语</option><option value="bs">波斯尼亚语</option><option value="fa">波斯语</option><option value="te">泰卢固语</option><option value="ta">泰米尔语</option><option value="th">泰语</option><option value="ht">海地克里奥尔语</option><option value="ga">爱尔兰语</option><option value="et">爱沙尼亚语</option><option value="sv">瑞典语</option><option value="be">白俄罗斯语</option><option value="lt">立陶宛语</option><option value="so">索马里语</option><option value="yo">约鲁巴语</option><option value="my">缅甸语</option><option value="ro">罗马尼亚语</option><option value="lo">老挝语</option><option value="fi">芬兰语</option><option value="hmn">苗语</option><option selected value="en">英语</option><option value="nl">荷兰语</option><option value="tl">菲律宾语</option><option value="pt">葡萄牙语</option><option value="mn">蒙古语</option><option value="es">西班牙语</option><option value="ha">豪萨语</option><option value="vi">越南语</option><option value="az">阿塞拜疆语</option><option value="sq">阿尔巴尼亚语</option><option value="ar">阿拉伯语</option><option value="ko">韩语</option><option value="mk">马其顿语</option><option value="mg">马尔加什语</option><option value="mr">马拉地语</option><option value="ml">马拉雅拉姆语</option><option value="ms">马来语</option><option value="mt">马耳他语</option><option value="km">高棉语</option><option value="ny">齐切瓦语</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="聆听翻译"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="复制译文"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="字体大小"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="帮助"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="固定弹出窗口"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">文本转语音功能仅限200个字符</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="显示翻译器的按钮 3 秒"> </div> + </td> + <td><a class="SL_options" title="显示选项">选项</a> : <a class="SL_options" title="翻译历史记录">历史</a> : <a class="SL_options" title="反馈">反馈</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="作出一点点贡献">Donate</a></td> + <td><span id="SL_Balloon_Close" title="关闭">关闭</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html new file mode 100644 index 0000000000..afa54c1aaf --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html @@ -0,0 +1,307 @@ +--- +title: runtime.onMessage +slug: Mozilla/Add-ons/WebExtensions/API/runtime/onMessage +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/onMessage +--- +<div>{{AddonSidebar()}}</div> + +<div>利用此事件来监听来自你的扩展其他部分的消息。例如,使用:</div> + +<div></div> + +<ul> + <li>in a <a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Content_scripts">content script</a>, to listen for messages from a <a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Background_scripts">background script.</a></li> + <li>in a background script, to listen for messages from a content script.</li> + <li>in an <a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Options_pages">options page</a> or <a href="/en-US/Add-ons/WebExtensions/User_interface_components#Popups">popup</a> script, to listen for messages from a background script.</li> + <li>in a background script, to listen for messages from an options page or popup script.</li> +</ul> + +<p>To send a message that is received by the <code>onMessage</code> listener, use {{WebExtAPIRef("runtime.sendMessage()")}} or (to send a message to a content script) {{WebExtAPIRef("tabs.sendMessage()")}}.</p> + +<div class="blockIndicator note"> +<p>Avoid creating multiple <code>onMessage</code> listeners for the same type of message, as the order in which multiple listeners will fire is not guaranteed. Where you want to guarantee the delivery of a message to a specific end point, use the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Connection-based_messaging">connection-based approach to exchange messages</a>.</p> +</div> + +<p>Along with the message itself, the listener is passed:</p> + +<ul> + <li>a <code>sender</code> object giving details about the message sender.</li> + <li>a <code>sendResponse</code> function that can be used to send a response back to the sender.</li> +</ul> + +<p>You can send a synchronous response to the message by calling the <code>sendResponse</code> function inside your listener. <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Sending_a_synchronous_response">See an example</a>.</p> + +<p>To send an asynchronous response, there are two options:</p> + +<ul> + <li>return <code>true</code> from the event listener. This keeps the <code>sendResponse</code> function valid after the listener returns, so you can call it later. <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Sending_an_asynchronous_response_using_sendResponse">See an example</a>.</li> + <li>return a <code>Promise</code> from the event listener, and resolve when you have the response (or reject it in case of an error). <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Sending_an_asynchronous_response_using_a_Promise">See an example</a>.</li> +</ul> + +<div class="warning"> +<p>Returning a <code>Promise</code> is now preferred as <code>sendResponse</code> <a href="https://github.com/mozilla/webextension-polyfill/issues/16#issuecomment-296693219">will be removed from the W3C spec</a>. The popular <a href="https://github.com/mozilla/webextension-polyfill">webextension-polyfill</a> library has already removed the <code>sendResponse</code> function from its implementation.</p> +</div> + +<div class="blockIndicator note"> +<p>You can also use a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Connection-based_messaging">connection-based approach to exchange messages</a>.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox brush:js">browser.runtime.onMessage.addListener(listener) +browser.runtime.onMessage.removeListener(listener) +browser.runtime.onMessage.hasListener(listener) +</pre> + +<p>Events have three functions:</p> + +<dl> + <dt><code>addListener(callback)</code></dt> + <dd>Adds a listener to this event.</dd> + <dt><code>removeListener(listener)</code></dt> + <dd>Stop listening to this event. The <code>listener</code> argument is the listener to remove.</dd> + <dt><code>hasListener(listener)</code></dt> + <dd>Checks whether a <code>listener</code> is registered for this event. Returns <code>true</code> if it is listening, <code>false</code> otherwise.</dd> +</dl> + +<h2 id="addListener_syntax">addListener syntax</h2> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>function</code></dt> + <dd> + <p>A listener function that will be called when this event occurs. The function will be passed the following arguments:</p> + + <dl class="reference-values"> + <dt><code>message</code></dt> + <dd><code>object</code>. The message itself. This is a JSON-ifiable object.</dd> + </dl> + + <dl class="reference-values"> + <dt><code>sender</code></dt> + <dd>A {{WebExtAPIRef('runtime.MessageSender')}} object representing the sender of the message.</dd> + </dl> + + <dl class="reference-values"> + <dt><code>sendResponse</code></dt> + <dd> + <p>A function to call, at most once, to send a response to the message. The function takes a single argument, which may be any JSON-ifiable object. This argument is passed back to the message sender.</p> + + <p>If you have more than one <code>onMessage</code> listener in the same document, then only one may send a response.</p> + + <p>To send a response synchronously, call <code>sendResponse</code> before the listener function returns. To send a response asynchronously:</p> + + <ul> + <li>either keep a reference to the <code>sendResponse</code> argument and return <code>true</code> from the listener function. You will then be able to call <code>sendResponse</code> after the listener function has returned.</li> + <li>or return a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> from the listener function and resolve the promise when the response is ready. This is a preferred way.</li> + </ul> + </dd> + </dl> + + <p>The listener function can return either a Boolean or a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>.</p> + + <div class="blockIndicator warning"> + <p>Do not call <code>addListener</code> using the <code>async</code> function, as in:</p> + + <pre><code>browser.runtime.onMessage.addListener(async (data, sender) => { + if (data.type === 'handle_me') return 'done'; +}); +</code></pre> + + <p>as the listener will consume every message it receives, effectively blocking all other listeners from receiving and processing messages.</p> + + <p>If you want to take an asynchronous approach, use a promise instead, as in:</p> + + <pre><code>browser.runtime.onMessage.addListener(data, sender) => { + if (data.type === 'handle_me') return Promise.resolve('done'); +}); +</code></pre> + </div> + </dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.onMessage")}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Simple_example">Simple example</h3> + +<p>This content script listens for click events on the web page. If the click was on a link, it messages the background page with the target URL:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// content-script.js</span> + +window<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">"click"</span><span class="punctuation token">,</span> notifyExtension<span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">notifyExtension</span><span class="punctuation token">(</span>e<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>e<span class="punctuation token">.</span>target<span class="punctuation token">.</span>tagName <span class="operator token">!=</span> <span class="string token">"A"</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + browser<span class="punctuation token">.</span>runtime<span class="punctuation token">.</span><span class="function token">sendMessage</span><span class="punctuation token">(</span><span class="punctuation token">{</span><span class="string token">"url"</span><span class="punctuation token">:</span> e<span class="punctuation token">.</span>target<span class="punctuation token">.</span>href<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">; +}</span></code> +</pre> + +<p>The background script listens for these messages and displays a notification using the <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications">notifications</a></code> API:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// background-script.js</span> + +browser<span class="punctuation token">.</span>runtime<span class="punctuation token">.</span>onMessage<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span>notify<span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="keyword token">function</span> <span class="function token">notify</span><span class="punctuation token">(</span>message<span class="punctuation token">)</span> <span class="punctuation token">{</span> + browser<span class="punctuation token">.</span>notifications<span class="punctuation token">.</span><span class="function token">create</span><span class="punctuation token">(</span><span class="punctuation token">{</span> + <span class="string token">"type"</span><span class="punctuation token">:</span> <span class="string token">"basic"</span><span class="punctuation token">,</span> + <span class="string token">"iconUrl"</span><span class="punctuation token">:</span> browser<span class="punctuation token">.</span>extension<span class="punctuation token">.</span><span class="function token">getURL</span><span class="punctuation token">(</span><span class="string token">"link.png"</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="string token">"title"</span><span class="punctuation token">:</span> <span class="string token">"You clicked a link!"</span><span class="punctuation token">,</span> + <span class="string token">"message"</span><span class="punctuation token">:</span> message<span class="punctuation token">.</span>url + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span></code></pre> + +<h3 id="Sending_a_synchronous_response">Sending a synchronous response</h3> + +<p>This content script sends a message to the background script when the user clicks on the page. It also logs any response sent by the background script:</p> + +<pre class="brush: js">// content-script.js + +function handleResponse(message) { + console.log(`background script sent a response: ${message.response}`); +} + +function handleError(error) { + console.log(`Error: ${error}`); +} + +function sendMessage(e) { + var sending = browser.runtime.sendMessage({content: "message from the content script"}); + sending.then(handleResponse, handleError); +} + +window.addEventListener("click", sendMessage);</pre> + +<p>Here is a version of the corresponding background script, that sends a response synchronously, from inside in the listener:</p> + +<pre class="brush: js">// background-script.js + +function handleMessage(request, sender, sendResponse) { + console.log(`content script sent a message: ${request.content}`); + sendResponse({response: "response from background script"}); +} + +browser.runtime.onMessage.addListener(handleMessage);</pre> + +<p>And here is another version, that uses Promise.resolve():</p> + +<pre class="brush: js">// background-script.js + +function handleMessage(request, sender, sendResponse) { + console.log(`content script sent a message: ${request.content}`); + return Promise.resolve({response: "response from background script"}); +} + +browser.runtime.onMessage.addListener(handleMessage);</pre> + +<h3 id="Sending_an_asynchronous_response_using_sendResponse">Sending an asynchronous response using sendResponse</h3> + +<p>Here is an alternative version of the background script from the previous example. It sends a response asynchronously after the listener has returned. Note <code>return true;</code> in the listener: this tells the browser that you intend to use the <code>sendResponse</code> argument after the listener has returned.</p> + +<pre class="brush: js">// background-script.js + +function handleMessage(request, sender, sendResponse) { + console.log(`content script sent a message: ${request.content}`); + setTimeout(() => { + sendResponse({response: "async response from background script"}); + }, 1000); + return true; +} + +browser.runtime.onMessage.addListener(handleMessage); +</pre> + +<h3 id="Sending_an_asynchronous_response_using_a_Promise">Sending an asynchronous response using a Promise</h3> + +<p>This content script gets the first <a> link on the page and sends a message asking if the link's location is bookmarked. It expects to get a Boolean response: <code>true</code> if the location is bookmarked, <code>false</code> otherwise:</p> + +<pre class="brush: js">// content-script.js + +const firstLink = document.querySelector("a"); + +function handleResponse(isBookmarked) { + if (isBookmarked) { + firstLink.classList.add("bookmarked"); + } +} + +browser.runtime.sendMessage({ + url: firstLink.href +}).then(handleResponse);</pre> + +<p>Here is the background script. It uses <code>{{WebExtAPIRef("bookmarks.search()")}}</code> to see if the link is bookmarked, which returns a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>:</p> + +<pre class="brush: js">// background-script.js + +function isBookmarked(message, sender, response) { + return browser.bookmarks.search({ + url: message.url + }).then(function(results) { + return results.length > 0; + }); +} + +browser.runtime.onMessage.addListener(isBookmarked);</pre> + +<p>If the asynchronous handler doesn't return a promise, you can explicitly construct a promise. This rather contrived example sends a response after a 1-second delay, using <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">Window.setTimeout()</a></code>:</p> + +<pre class="brush: js">// background-script.js + +function handleMessage(request, sender, sendResponse) { + return new Promise(resolve => { + setTimeout(() => { + resolve({response: "async response from background script"}); + }, 1000); + }); +} + +browser.runtime.onMessage.addListener(handleMessage);</pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#event-onMessage"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/openoptionspage/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/openoptionspage/index.html new file mode 100644 index 0000000000..701af9c2ea --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/openoptionspage/index.html @@ -0,0 +1,92 @@ +--- +title: runtime.openOptionsPage() +slug: Mozilla/Add-ons/WebExtensions/API/runtime/openOptionsPage +tags: + - API + - OpenPractices + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/openOptionsPage +--- +<div> </div> + +<div>假如你的页面有<a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Options_pages">options page</a>(设置页面)的定义,使用此方法打开它。</div> + +<div> </div> + +<div>这是一个异步方法,返回一个 <code style="font-style: normal; font-weight: normal;"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>对象</code></div> + +<div> </div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox brush:js">var openingPage = browser.runtime.openOptionsPage() +</pre> + +<h3 id="参数">参数</h3> + +<p>无</p> + +<h3 id="返回值">返回值</h3> + +<p><code>当设置页面成功创建,执行<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>的无参成功回调方法,否则执行<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>的失败回调方法,参数为错误信息。</code></p> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.openOptionsPage")}}</p> + +<h2 id="例子">例子</h2> + +<p>当用户点击浏览器行为图标时,打开一个设置页面。</p> + +<pre class="brush: js">function onOpened() { + console.log(`Options page opened`); +} + +function onError(error) { + console.log(`Error: ${error}`); +} + +var opening = browser.runtime.openOptionsPage(); +opening.then(onOpened, onError);</pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#method-openOptionsPage"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/platformarch/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/platformarch/index.html new file mode 100644 index 0000000000..0adfaf39f1 --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/platformarch/index.html @@ -0,0 +1,70 @@ +--- +title: 获取处理器架构 - runtime.PlatformArch +slug: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformArch +tags: + - 获取处理器架构 + - 附加组件 +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformArch +--- +<div>{{AddonSidebar()}}</div> + +<p>当前浏览器所在的计算机的处理器架构.</p> + +<h2 id="值类型">值类型</h2> + +<p>该值的类型是字符串. 可能的值如下:</p> + +<dl> + <dt><code>"arm"</code></dt> + <dd>标识平台基于 arm 架构.</dd> + <dt><code>"x86-32"</code></dt> + <dd>表示平台基于 x86 32-bit 架构.</dd> + <dt><code>"x86-64"</code></dt> + <dd>表示平台基于 x86 64-bit 架构.</dd> +</dl> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.PlatformArch")}}</p> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#type-PlatformArch"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/platformos/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/platformos/index.html new file mode 100644 index 0000000000..6c32d46b6f --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/platformos/index.html @@ -0,0 +1,76 @@ +--- +title: 获取当前操作系统 - runtime.PlatformOs +slug: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformOs +tags: + - 获取当前操作系统 + - 附加组件 +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/PlatformOs +--- +<div>{{AddonSidebar()}}</div> + +<p>获取当前浏览器运行所在的操作系统.</p> + +<h2 id="值类型">值类型</h2> + +<p>该值的类型是字符串. 可能的值如下:</p> + +<dl> + <dt><code>"mac"</code></dt> + <dd>表示底层操作系统是 Mac OS X.</dd> + <dt><code>"win"</code></dt> + <dd>表示底层操作系统是 Windows.</dd> + <dt><code>"android"</code></dt> + <dd>表示底层操作系统是 Android.</dd> + <dt><code>"cros"</code></dt> + <dd>表示底层操作系统是 Chrome OS.</dd> + <dt><code>"linux"</code></dt> + <dd>表示底层操作系统是 Linux.</dd> + <dt><code>"openbsd"</code></dt> + <dd>表示底层操作系统是 Open/FreeBSD.</dd> +</dl> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.PlatformOs")}}</p> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#type-PlatformOs"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendmessage/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendmessage/index.html new file mode 100644 index 0000000000..86ec753075 --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendmessage/index.html @@ -0,0 +1,157 @@ +--- +title: runtime.sendMessage() +slug: Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage +--- +<div>{{AddonSidebar()}}</div> + +<div>向你的扩展或其他扩展发送单条消息。</div> + +<div> </div> + +<div>如果想发给你自己的扩展,则省略 <code>extensionId</code> 参数。扩展中所有页面的{{WebExtAPIRef('runtime.onMessage')}}将会被触发,除了调用<code>runtime.sendMessage的页面。</code></div> + +<p> </p> + +<p>如果发送给其他扩展,则将参数 <code>extensionId</code> 设置为其他扩展的ID。其他扩展的 {{WebExtAPIRef('runtime.onMessageExternal')}} 将会被触发。</p> + +<p>此接口不能给 content script 发消息,如果要给 content script 发消息,请使用 {{WebExtAPIRef('tabs.sendMessage')}}。</p> + +<p>这是个异步方法,将返回一个 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>。</p> + +<p>Syntax</p> + +<pre class="syntaxbox brush:js">var sending = browser.runtime.sendMessage( + extensionId, // optional string + message, // any + options // optional object +) +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>extensionId</code>{{optional_inline}}</dt> + <dd><code>string</code>. 若你想要发给不同的扩展,这里传入接收方的扩展ID。The ID of the extension to send the message to. Include this to send the message to a different extension. If the intended recipient has set an ID explicitly using the <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/applications">applications</a> key in manifest.json, then <code>extensionId</code> should have this value. Otherwise it should be have the ID that was generated for the intended recipient.</dd> + <dd>若此省略此参数,则发送给自己的扩展。</dd> + <dt><code>message</code></dt> + <dd><code>any</code>. 任何可以序列化成JSON的东西。</dd> + <dt><code>options</code>{{optional_inline}}</dt> + <dd><code>object</code>. + <dl class="reference-values"> + <dt><code>includeTlsChannelId</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. Whether the TLS channel ID will be passed into {{WebExtAPIRef('runtime.onMessageExternal')}} for processes that are listening for the connection event.</dd> + <dt><code>toProxyScript{{optional_inline}}</code></dt> + <dd><code>boolean</code>. Must be True if the message is intended for a PAC file loaded using the {{WebExtAPIRef("proxy")}} API.</dd> + </dl> + </dd> +</dl> + +<p>根据给出的参数不同,API遵循如下规则:</p> + +<ul> + <li><strong>只有1个参数:</strong>将会被当做 message 发送给自己的扩展。</li> + <li><strong>有2个参数:</strong> + <ul> + <li>若第二个参数符合下面的规则,将会被当做 <code>(message, options)</code>,将消息发送给自己的扩展: + <ol> + <li>一个合法的配置对象(也就是说这个对象只包含options参数支持的属性)</li> + <li>null</li> + <li>undefined</li> + </ol> + </li> + <li>否则,将会被当做 <code>(extensionId, message)。</code>消息将会给发送给 <code>extensionId</code> 指定ID的扩展</li> + </ul> + </li> + <li><strong>有3个参数:</strong>将会被当做 <code>(extensionId, message, options)</code>. 消息将会给发送给 <code>extensionId</code> 指定ID的扩展</li> +</ul> + +<div class="note"> +<p>在Firefox 55之前,只给出2个参数时,规则会有所不同:<br> + Under the old rules, if the first argument was a string, it was treated as the <code>extensionId</code>, with the message as the second argument. This meant that if you called <code>sendMessage()</code> with arguments like <code>("my-message", {})</code>, then it would send an empty message to the extension identified by "my-message". Under the new rules, with these arguments you would send the message "my-message" internally, with an empty options object.</p> +</div> + +<h3 id="Return_value">Return value</h3> + +<p>返回一个 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>。若接收方响应,Promise将会变为 fulfilled 并且返回接收方响应的JSON对象(数字、字符串、数组、true/false都是合法的JSON对象)。否则,Promise会变为 fulfilled 但是不返回任何参数。如果发生了连接错误,Promise将会变为 rejected 并返回一个错误消息。</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("webextensions.api.runtime.sendMessage")}}</p> + +<h2 id="Examples">Examples</h2> + +<p>Here's a content script that sends a message to the background script when the user clicks the content window. The message payload is <code>{greeting: "Greeting from the content script"}</code>, and the sender also expects to get a response, which is handled in the <code>handleResponse</code> function:</p> + +<pre class="brush: js">// content-script.js + +function handleResponse(message) { + console.log(`Message from the background script: ${message.response}`); +} + +function handleError(error) { + console.log(`Error: ${error}`); +} + +function notifyBackgroundPage(e) { + var sending = browser.runtime.sendMessage({ + greeting: "Greeting from the content script" + }); + sending.then(handleResponse, handleError); +} + +window.addEventListener("click", notifyBackgroundPage);</pre> + +<p>The corresponding background script looks like this:</p> + +<pre class="brush: js">// background-script.js + +function handleMessage(request, sender, sendResponse) { + console.log("Message from the content script: " + + request.greeting); + sendResponse({response: "Response from background script"}); +} + +browser.runtime.onMessage.addListener(handleMessage);</pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#method-sendMessage"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p> + +<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> diff --git a/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendnativemessage/index.html b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendnativemessage/index.html new file mode 100644 index 0000000000..349b7a06d0 --- /dev/null +++ b/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendnativemessage/index.html @@ -0,0 +1,109 @@ +--- +title: runtime.sendNativeMessage() +slug: Mozilla/Add-ons/WebExtensions/API/runtime/sendNativeMessage +tags: + - sendNativeMessage + - 扩展 + - 附加组件 + - 非标准 +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/sendNativeMessage +--- +<div>{{AddonSidebar()}}</div> + +<p>从 WebExtension 发送单条消息到 native application。</p> + +<p>它需要两个强制的参数:native application 的名字和要发送给它的JSON对象。浏览器将会加载 native application 然后发送这个消息。</p> + +<p>这是一个异步函数,返回一个 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>对象。native application 发送的第一条消息将被当作<code>sendNativeMessage()</code> 的回复,并且 promise 将这个消息作为参数.。注意你不能使用 {{WebExtAPIRef("runtime.onMessage")}} 从应用获取回复:你必须使用回调函数来替代。</p> + +<p>每次调用 <code>runtime.sendNativeMessage()</code>都会生成一个新的实例。浏览器将会在收到回复后结束这个 native application。为了结束这个 native application,浏览器将会关闭 pipe,并给进程几秒的时间优雅的退出,如果它没有关闭就杀死它。</p> + +<p>更对信息,参考 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging">Native messaging</a>。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox brush:js">var sending = browser.runtime.sendNativeMessage( + application, // string + message // object +) +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>application</code></dt> + <dd><code>字符串类型。</code>native application的名字。它必须和 <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Native_messaging#App_manifest">native application's manifest file</a>中的‘name’字段一致。</dd> + <dt><code>message</code></dt> + <dd><code>对象类型。一个将要发送给</code> native application的JSON对象。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>一个 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>对象。如果native application发送了一个回复,它将会填充回复的JSON对象作为参数。否则它不会填充参数。如果在native application连接期间发生了错误,promise将会被一个错误的消息拒绝。</p> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">这个页面的兼容性表从结构性数据生成的。如果你想提供数据,请访问 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 然后提交请求。</p> + +<p>{{Compat("webextensions.api.runtime.sendNativeMessage")}}</p> + +<h2 id="示例">示例</h2> + +<p>这是一个 background script ,当使用者点击浏览器的browser action时,它会发送 "ping" 消息到 "ping_pong" 应用并且把回复记录下来:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">onResponse</span><span class="punctuation token">(</span>response<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">`Received ${</span>response}<span class="punctuation token">`)</span><span class="punctuation token">;</span> +<span class="punctuation token">} + +</span></code>function onError(error) { + console.log(`Error: ${error}`); +}<code class="language-js"> + +<span class="comment token">/* +On a click on the browser action, send the app a message. +*/</span> +browser<span class="punctuation token">.</span>browserAction<span class="punctuation token">.</span>onClicked<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"Sending: ping"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + var sending = browser<span class="punctuation token">.</span>runtime<span class="punctuation token">.</span><span class="function token">sendNativeMessage</span><span class="punctuation token">(</span><span class="string token">"ping_pong"</span><span class="punctuation token">,</span> <span class="string token">"ping"</span><span class="punctuation token">)</span><span class="punctuation token">; + sending.then(onResponse, onError);</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>这个API 基于 Chromium 的 <a href="https://developer.chrome.com/extensions/runtime#method-sendNativeMessage"><code>chrome.runtime</code></a> API。 本文来自 Chromium 代码中的 <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> 。</p> + +<p>微软 Edge 的兼容性数据由 Microsoft Corporation 提供,并且包含在这里基于 Creative Commons Attribution 3.0 United States License。</p> +</div> + +<div class="hidden"> +<pre>// Copyright 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +</pre> +</div> |