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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
|
---
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>
<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>{{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>
|