aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/mozilla/add-ons/webextensions/api/runtime/sendmessage/index.html
blob: 2f104f7a32effed6810317fbee66f161b8618fac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
---
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>{{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>