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
|
---
title: webRequest.onBeforeRequest
slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest
translation_of: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest
---
<div>{{AddonSidebar()}}</div>
<p>This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.</p>
<p>To cancel or redirect the request, first include <code>"blocking"</code> in the <code>extraInfoSpec</code> array argument to <code>addListener()</code>. Then, in the listener function, return a {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} object, setting the appropriate property:</p>
<ul>
<li>to cancel the request, include a property <code>cancel</code> with the value <code>true</code>.</li>
<li>to redirect the request, include a property <code>redirectUrl</code> with the value set to the URL to which you want to redirect.</li>
</ul>
<p>From Firefox 52 onwards, instead of returning <code>BlockingResponse</code>, the listener can return a <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> which is resolved with a <code>BlockingResponse</code>. This enables the listener to process the request asynchronously.</p>
<p>If you use <code>"blocking"</code>, you must have the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">"webRequestBlocking" API permission</a> in your manifest.json.</p>
<h2 id="문법">문법</h2>
<pre class="syntaxbox brush:js">browser.webRequest.onBeforeRequest.addListener(
listener, // function
filter, // object
extraInfoSpec // optional array of strings
)
browser.webRequest.onBeforeRequest.removeListener(listener)
browser.webRequest.onBeforeRequest.hasListener(listener)
</pre>
<p>Events have three functions:</p>
<dl>
<dt><code>addListener(callback, filter, extraInfoSpec)</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>Check whether <code>listener</code> is registered for this event. Returns <code>true</code> if it is listening, <code>false</code> otherwise.</dd>
</dl>
<h2 id="리스너_등록_문법">리스너 등록 문법</h2>
<h3 id="Parameters">Parameters</h3>
<dl>
<dt><code>callback</code></dt>
<dd>
<p>Function that will be called when this event occurs. The function will be passed the following arguments:</p>
<dl class="reference-values">
<dt><code>details</code></dt>
<dd><a href="#details"><code>object</code></a>. Details about the request. See <code><a href="#details">details</a></code> below.</dd>
</dl>
<p>Returns: {{WebExtAPIRef('webRequest.BlockingResponse')}}. If <code>"blocking"</code> is specified in the <code>extraInfoSpec</code> parameter, the event listener should return a <code>BlockingResponse</code> object, and can set either its <code>cancel</code> or its <code>redirectUrl</code> properties. From Firefox 52 onwards, instead of returning <code>BlockingResponse</code>, the listener can return a <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> which is resolved with a <code>BlockingResponse</code>. This enables the listener to process the request asynchronously.</p>
</dd>
<dt><code>filter</code></dt>
<dd>{{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that will be sent to this listener.</dd>
<dt><code>extraInfoSpec</code>{{optional_inline}}</dt>
<dd><code>array</code> of <code>string</code>. <span class="im">Extra options for the event. You can pass any of the following values:</span></dd>
<dd>
<ul>
<li><code>"blocking"</code>: make the request synchronous, so you can cancel or redirect the request</li>
<li><span class="im"><code>"requestBody"</code>: include <code>requestBody</code> in the <code>details</code> object passed to the listener</span></li>
</ul>
</dd>
</dl>
<h2 id="추가적인_객체">추가적인 객체</h2>
<h3 id="details">details</h3>
<dl class="reference-values">
<dt><code>requestId</code></dt>
<dd><code>string</code>. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.</dd>
<dt><code>url</code></dt>
<dd><code>string</code>. Target of the request.</dd>
<dt><code>method</code></dt>
<dd><code>string</code>. Standard HTTP method: for example, "GET" or "POST".</dd>
<dt><code>frameId</code></dt>
<dd><code>integer</code>. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.</dd>
<dt><code>parentFrameId</code></dt>
<dd><code>integer</code>. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.</dd>
<dt><code>requestBody</code>{{optional_inline}}</dt>
<dd><code>object</code>. Contains the HTTP request body data. Only provided if <code>extraInfoSpec</code> contains <code>"requestBody"</code>.</dd>
<dd>
<dl class="reference-values">
<dt><code>error</code>{{optional_inline}}</dt>
<dd><code>string</code>. This is set if any errors were encountered when obtaining request body data.</dd>
<dt><code>formData</code>{{optional_inline}}</dt>
<dd><code>object</code>. This object is present if the request method is POST and the body is a sequence of key-value pairs encoded in UTF-8 as either "multipart/form-data" or "application/x-www-form-urlencoded".</dd>
<dd>It is a dictionary in which each key contains the list of all values for that key. For example: <code>{'key': ['value1', 'value2']}</code>. If the data is of another media type, or if it is malformed, the object is not present.</dd>
<dt><code>raw</code>{{optional_inline}}</dt>
<dd><code>array</code> of <code>{{WebExtAPIRef('webRequest.UploadData')}}</code>. If the request method is PUT or POST, and the body is not already parsed in <code>formData</code>, then this array contains the unparsed request body elements.</dd>
</dl>
</dd>
<dt><code>tabId</code></dt>
<dd><code>integer</code>. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.</dd>
<dt><code>type</code></dt>
<dd>{{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet".</dd>
<dt><code>timeStamp</code></dt>
<dd><code>number</code>. The time when this event fired, in <a href="https://en.wikipedia.org/wiki/Unix_time">milliseconds since the epoch</a>.</dd>
<dt><code>originUrl</code></dt>
<dd><code>string</code>. URL of the resource that triggered this request. Note that this may not be the same as the URL of the page into which the requested resource will be loaded. For example, if a document triggers a load in a different window through the <a href="/en-US/docs/Web/HTML/Element/a#attr-target">target attribute of a link</a>, or a CSS document includes an image using the <a href="/en-US/docs/Web/CSS/url#The_url()_functional_notation"><code>url()</code> functional notation</a>, then this will be the URL of the original document or of the CSS document, respectively.</dd>
</dl>
<h2 id="브라우저_호환성">브라우저 호환성</h2>
<p>{{Compat("webextensions.api.webRequest.onBeforeRequest", 10)}}</p>
<h2 id="예제">예제</h2>
<p>This code logs the URL for every resource requested which matches the <a href="/en-US/Add-ons/WebExtensions/Match_patterns#<all_urls>"><all_urls></a> pattern:</p>
<pre class="brush: js">function logURL(requestDetails) {
console.log("Loading: " + requestDetails.url);
}
browser.webRequest.onBeforeRequest.addListener(
logURL,
{urls: ["<all_urls>"]}
);</pre>
<p>This code cancels requests for images that are made to URLs under "https://mdn.mozillademos.org/" (to see the effect, visit any page on MDN that contains images, such as <a href="/en-US/docs/Mozilla/Firefox/Developer_Edition">Firefox Developer Edition</a>):</p>
<pre class="brush: js">// match pattern for the URLs to redirect
var pattern = "https://mdn.mozillademos.org/*";
// cancel function returns an object
// which contains a property `cancel` set to `true`
function cancel(requestDetails) {
console.log("Canceling: " + requestDetails.url);
return {cancel: true};
}
// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
cancel,
{urls: [pattern], types: ["image"]},
["blocking"]
);
</pre>
<p>This code replaces, by redirection, all network requests for images that are made to URLs under "https://mdn.mozillademos.org/" (to see the effect, visit any page on MDN that contains images, such as <a href="/en-US/docs/Mozilla/Firefox/Developer_Edition">Firefox Developer Edition</a>):</p>
<pre class="brush: js">// match pattern for the URLs to redirect
var pattern = "https://mdn.mozillademos.org/*";
// redirect function
// returns an object with a property `redirectURL`
// set to the new URL
function redirect(requestDetails) {
console.log("Redirecting: " + requestDetails.url);
return {
redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
};
}
// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
redirect,
{urls:[pattern], types:["image"]},
["blocking"]
);</pre>
<p>This code is exactly like the previous example, except that the listener handles the request asynchronously. It returns a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> that sets a timer, and resolves with the redirect URL when the timer expires:</p>
<pre class="brush: js">// match pattern for the URLs to redirect
var pattern = "https://mdn.mozillademos.org/*";
// URL we will redirect to
var redirectUrl = "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif";
// redirect function returns a Promise
// which is resolved with the redirect URL when a timer expires
function redirectAsync(requestDetails) {
console.log("Redirecting async: " + requestDetails.url);
var asyncCancel = new Promise((resolve, reject) => {
window.setTimeout(() => {
resolve({redirectUrl});
}, 2000);
});
return asyncCancel;
}
// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
redirectAsync,
{urls: [pattern], types: ["image"]},
["blocking"]
);</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/webRequest#event-onBeforeRequest"><code>chrome.webRequest</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.json"><code>web_request.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>
|