diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/mozilla/add-ons/webextensions/api/webrequest | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/ru/mozilla/add-ons/webextensions/api/webrequest')
-rw-r--r-- | files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html | 188 |
1 files changed, 188 insertions, 0 deletions
diff --git a/files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html b/files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html new file mode 100644 index 0000000000..3f0da7eada --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html @@ -0,0 +1,188 @@ +--- +title: ВебЗапрос +slug: Mozilla/Add-ons/WebExtensions/API/webRequest +translation_of: Mozilla/Add-ons/WebExtensions/API/webRequest +--- +<div>{{AddonSidebar}}</div> + +<p>Добавляет обработчики событий на различных стадиях HTTP запроса. Обработчик получет детальную информацию о запросе и способен изменить или отменить запрос.</p> + +<p>Каждое событие запущено на определённой стадии запроса. Типичный порядок событий такой:<img alt="" src="https://mdn.mozillademos.org/files/13376/webRequest-flow.png" style="display: block; height: 680px; margin-left: auto; margin-right: auto; width: 624px;"></p> + +<p>{{WebExtAPIRef("webRequest.onErrorOccurred", "onErrorOccurred")}} Может быть запущен в любой момент во время запроса. Чреда событий может отличаться от приведенной выше: например, в Firefox, после <a href="/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">HSTS</a> обновления, событие <code>onBeforeRedirect</code> будет запущено сразу же после <code>onBeforeRequest</code>.</p> + +<p>Все события, кроме <code>onErrorOccurred</code>, могут принимать три аргумента в <code>addListener()</code>:</p> + +<ul> + <li>сам обработчик</li> + <li>обьект {{WebExtAPIRef("webRequest.RequestFilter", "filter")}} , который позволяет получать оповещения о запросах, сделанных к определённым URL или определённым типам ресурсов.</li> + <li>необязательный обьект <code>extraInfoSpec</code> . Может быть использован для передачи дополнительных срецифических для события инструкций.</li> +</ul> + +<p>Функции - обработчику передается обьект <code>details</code> который содержит информацию о запросе. Она содержит ID запроса, который обеспечен для включения надстройки, которая позволяет соотносить события, ассоциируемые с одним запросом. Это уникально в пределах сессии и контекста надстройки. Информация остается одинаковой везде на протяжении запроса, даже при перенаправлениях и обменах аутентификации.</p> + +<p>Для использования webRequest API для определённого хоста, расширение должно иметь "webRequest" <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">API permission</a> и <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission </a>для этого хоста. Для использования возможности "блокирования" расширение должно также иметь "webRequestBlocking" API разрешение.</p> + +<p>Для перехвата ресурсов, загруженных страницей (таких как картинки, скрипты или таблицы стилей), расширение должно иметь разрешение хоста для ресурса также как и для главной страницы, запрашивающей ресурс. К примеру, если страница на "https://developer.mozilla.org" загружает картинку из "https://mdn.mozillademos.org", тогда расширение должно иметь разрешения обоих хостов чтобы перехватить запрос картинки.</p> + +<h2 id="Модифицирование_заголовков">Модифицирование заголовков</h2> + +<p>Используя некоторые из этих событий, вы можете модифицировать запрос. Конкретно, вы можете:</p> + +<ul> + <li>отменить запрос в: + <ul> + <li>{{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}}</li> + <li>{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}</li> + <li>{{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}}</li> + </ul> + </li> + <li>перенаправить запрос в: + <ul> + <li>{{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}}</li> + <li>{{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}</li> + </ul> + </li> + <li>модифицировать заголовки запроса в: + <ul> + <li>{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} + <ul> + </ul> + </li> + </ul> + </li> + <li>модифицировать заголовки ответа в: + <ul> + <li>{{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}</li> + </ul> + </li> + <li>предоставить учетные данные аутентификации в: + <ul> + <li>{{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}}</li> + </ul> + </li> +</ul> + +<p>Чтобы сделать это, вам необходимо передать оцпию со значением "blocking" в аргументе <code>extraInfoSpec</code> к <code>addListener()</code>. Это делает обработчик синхронным. В обработчике, вы можете тогда возвратить обьект {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} который индикует модификацию, какую вам нужно сделать: например, модифицированный заголовок запроса который вы хотите отправить.</p> + +<h2 id="Доступ_к_информации_о_безопасности">Доступ к информации о безопасности</h2> + +<p>В обработчике {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}} вы имеете доступ к <a href="/en-US/docs/Glossary/TLS">TLS</a> свойствам запроса через вызов {{WebExtAPIRef("webRequest.getSecurityInfo()", "getSecurityInfo()")}}. Чтоды сделать это, вы должны также передать "blocking" в <code>extraInfoSpec</code> аргументе к <code>addListener()</code> события.</p> + +<p>Вы можете прочитать детали TLS хэндшейка, но не можете модифицировать их или перезаписать решения доверы браузера.</p> + +<h2 id="Modifying_responses">Modifying responses</h2> + +<p>Для того, чтобы модифицировать тело HTTP ответа на запрос, вызовите {{WebExtAPIRef("webRequest.filterResponseData")}}, и передайте ID запроса. Это возвратит обьект {{WebExtAPIRef("webRequest.StreamFilter")}} который вы сможете использовать чтобы исследовать и изменять данные когда они получены браузером.</p> + +<p>Чтобы сделать это, у вас дожно быть "webRequestBlocking" API разрешение, а также "webRequest" <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">API permission</a> и <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission </a>от соответствующего хоста.</p> + +<h2 id="Types">Types</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.BlockingResponse")}}</dt> + <dd> + <p>An object of this type is returned by event listeners that have set <code>"blocking"</code> in their <code>extraInfoSpec</code> argument. By setting particular properties in <code>BlockingResponse</code>, the listener can modify network requests.</p> + </dd> + <dt>{{WebExtAPIRef("webRequest.CertificateInfo")}}</dt> + <dd>An object describing a single X.509 certificate.</dd> + <dt>{{WebExtAPIRef("webRequest.HttpHeaders")}}</dt> + <dd>An array of HTTP headers. Each header is represented as an object with two properties: <code>name</code> and either <code>value</code> or <code>binaryValue</code>.</dd> + <dt>{{WebExtAPIRef("webRequest.RequestFilter")}}</dt> + <dd>An object describing filters to apply to webRequest events.</dd> + <dt>{{WebExtAPIRef("webRequest.ResourceType")}}</dt> + <dd>Represents a particular kind of resource fetched in a web request.</dd> + <dt>{{WebExtAPIRef("webRequest.SecurityInfo")}}</dt> + <dd>An object describing the security properties of a particular web request.</dd> + <dt>{{WebExtAPIRef("webRequest.StreamFilter")}}</dt> + <dd>An object that can be used to monitor and modify HTTP responses while they are being received.</dd> + <dt>{{WebExtAPIRef("webRequest.UploadData")}}</dt> + <dd>Contains data uploaded in a URL request.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES")}}</dt> + <dd>The maximum number of times that <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/WebRequest/handlerBehaviorChanged" title="Suppose an add-on's job is to block web requests against a pattern, and the following scenario happens:"><code>handlerBehaviorChanged()</code></a></code> can be called in a 10 minute period.</dd> +</dl> + +<h2 id="Functions">Functions</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.handlerBehaviorChanged()")}}</dt> + <dd>This function can be used to ensure that event listeners are applied correctly when pages are in the browser's in-memory cache.</dd> + <dt>{{WebExtAPIRef("webRequest.filterResponseData()")}}</dt> + <dd>Returns a {{WebExtAPIRef("webRequest.StreamFilter")}} object for a given request.</dd> + <dt>{{WebExtAPIRef("webRequest.getSecurityInfo()")}}</dt> + <dd>Gets detailed information about the <a href="/en-US/docs/Glossary/TLS">TLS</a> connection associated with a given request.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.onBeforeRequest")}}</dt> + <dd>Fired 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.</dd> + <dt>{{WebExtAPIRef("webRequest.onBeforeSendHeaders")}}</dt> + <dd>Fired before sending any HTTP data, but after HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers.</dd> + <dt>{{WebExtAPIRef("webRequest.onSendHeaders")}}</dt> + <dd>Fired just before sending headers. If your add-on or some other add-on modified headers in <code>{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}</code>, you'll see the modified version here.</dd> + <dt>{{WebExtAPIRef("webRequest.onHeadersReceived")}}</dt> + <dd>Fired when the HTTP response headers associated with a request have been received. You can use this event to modify HTTP response headers.</dd> + <dt>{{WebExtAPIRef("webRequest.onAuthRequired")}}</dt> + <dd>Fired when the server asks the client to provide authentication credentials. The listener can do nothing, cancel the request, or supply authentication credentials.</dd> + <dt>{{WebExtAPIRef("webRequest.onResponseStarted")}}</dt> + <dd>Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available.</dd> + <dt>{{WebExtAPIRef("webRequest.onBeforeRedirect")}}</dt> + <dd>Fired when a server-initiated redirect is about to occur.</dd> + <dt>{{WebExtAPIRef("webRequest.onCompleted")}}</dt> + <dd>Fired when a request is completed.</dd> + <dt>{{WebExtAPIRef("webRequest.onErrorOccurred")}}</dt> + <dd>Fired when an error occurs.</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("webextensions.api.webRequest")}}</p> + +<p><a href="/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#webRequest_incompatibilities">Extra notes on Chrome incompatibilities</a>.</p> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/webRequest"><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 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> |