chrome.webRequest – Chrome Developers

Use the chrome.webRequest API to observe and analyze traffic and to intercept, blocking, or modify requests in-flight. You must declare the “ webRequest ” permission in the extension manifest to use the web request API, along with the necessity host permissions. To intercept a sub-resource request, the annex needs to have access to both the requested URL and its instigator. If you want to use the web request API in a jam fashion, you need to request the “ webRequestBlocking ” permission in addition. For model :

 {
`` name '' : `` My extension '' ,
...
`` permissions '' : [
`` webRequest '' ,
`` * : //*.google.com/ ''
] ,
...
}

# Life cycle of requests

The web request API defines a located of events that follow the life cycle of a web request. You can use these events to observe and analyze traffic. Certain synchronous events will allow you to intercept, engine block, or modify a request. The event animation cycle for successful requests is illustrated here, followed by event definitions : Life cycle of a web request from the perspective of the webrequest API

onBeforeRequest (optionally synchronous)
Fires when a request is about to occur. This event is sent before any TCP connection is made and can be used to cancel or redirect requests.
onBeforeSendHeaders (optionally synchronous)
Fires when a request is about to occur and the initial headers have been prepared. The event is intended to allow extensions to add, modify, and delete request headers (*). The onBeforeSendHeaders event is passed to all subscribers, so different subscribers may attempt to modify the request; see the Implementation details section for how this is handled. This event can be used to cancel the request.
onSendHeaders
Fires after all extensions have had a chance to modify the request headers, and presents the final (*) version. The event is triggered before the headers are sent to the network. This event is informational and handled asynchronously. It does not allow modifying or cancelling the request.
onHeadersReceived (optionally synchronous)
Fires each time that an HTTP(S) response header is received. Due to redirects and authentication requests this can happen multiple times per request. This event is intended to allow extensions to add, modify, and delete response headers, such as incoming Content-Type headers. The caching directives are processed before this event is triggered, so modifying headers such as Cache-Control has no influence on the browser’s cache. It also allows you to cancel or redirect the request.
onAuthRequired (optionally synchronous)
Fires when a request requires authentication of the user. This event can be handled synchronously to provide authentication credentials. Note that extensions may provide invalid credentials. Take care not to enter an infinite loop by repeatedly providing invalid credentials. This can also be used to cancel the request.
onBeforeRedirect
Fires when a redirect is about to be executed. A redirection can be triggered by an HTTP response code or by an extension. This event is informational and handled asynchronously. It does not allow you to modify or cancel the request.
onResponseStarted
Fires when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available. This event is informational and handled asynchronously. It does not allow modifying or cancelling the request.
onCompleted
Fires when a request has been processed successfully.
onErrorOccurred
Fires when a request could not be processed successfully.

The network request API guarantees that for each request either onCompleted or onErrorOccurred is fired as the final examination consequence with one exception : If a request is redirected to a data:// URL, onBeforeRedirect is the final report consequence. note that the web request API presents an abstraction of the network stack to the extension. internally, one URL request can be split into several HTTP requests ( for exemplar to fetch individual byte ranges from a boastfully file ) or can be handled by the network smokestack without communicating with the network. For this reason, the API does not provide the final HTTP headers that are sent to the network. For exercise, all headers that are related to caching are invisible to the propagation. The pursuit headers are presently not provided to the onBeforeSendHeaders consequence. This list is not guaranteed to be complete nor stable .

  • Authorization
  • Cache-Control
  • Connection
  • Content-Length
  • Host
  • If-Modified-Since
  • If-None-Match
  • If-Range
  • Partial-Data
  • Pragma
  • Proxy-Authorization
  • Proxy-Connection
  • Transfer-Encoding

Starting from Chrome 79, request header modifications affect Cross-Origin Resource Sharing ( CORS ) checks. If modified headers for cross-origin requests do not meet the criteria, it will result in sending a CORS preflight to ask the server if such headers can be accepted. If you actually need to modify headers in a way to violate the CORS protocol, you need to specify 'extraHeaders' in opt_extraInfoSpec. On the other hand, response header modifications do not work to deceive CORS checks. If you need to deceive the CORS protocol, you besides need to specify 'extraHeaders' for the response modifications. Starting from Chrome 79, the webRequest API does not intercept CORS preflight requests and responses by nonpayment. A CORS preflight for a request URL is visible to an extension if there is a hearer with 'extraHeaders' specified in opt_extraInfoSpec for the request URL. onBeforeRequest can besides take 'extraHeaders' from Chrome 79. Starting from Chrome 79, the following request header is not provided and can not be modified or removed without specifying 'extraHeaders' in opt_extraInfoSpec :

  • Origin

Note: Modifying the Origin request heading might not work deoxyadenosine monophosphate intended and may result in unexpected errors in the answer ‘s CORS checks. This is because while extensions can only modify the Origin request header, they ca n’t change the request origin or instigator, which is a concept defined in the Fetch specification to represent who initiates the request. In such a scenario, the waiter may allow the CORS entree for the change request and put the header ‘s Origin into the Access-Control-Allow-Origin header in the answer. But it wo n’t match the immutable request origin and result in a CORS failure. Starting from Chrome 72, if you need to modify responses before Cross Origin Read Blocking ( CORB ) can block the response, you need to specify 'extraHeaders' in opt_extraInfoSpec. Starting from Chrome 72, the postdate request headers are not provided and can not be modified or removed without specifying 'extraHeaders' in opt_extraInfoSpec :

  • Accept-Language
  • Accept-Encoding
  • Referer
  • Cookie

Starting from Chrome 72, the Set-Cookie response header is not provided and can not be modified or removed without specifying 'extraHeaders' in opt_extraInfoSpec. Starting from Chrome 89, the X-Frame-Options response header can not be efficaciously modified or removed without specifying 'extraHeaders' in opt_extraInfoSpec. Note: Specifying 'extraHeaders' in opt_extraInfoSpec may have a negative impact on performance, hence it should only be used when actually necessary. The webRequest API only exposes requests that the extension has license to see, given its host permissions. furthermore, alone the take after schemes are accessible : http://, https://, ftp://, file://, ws:// ( since Chrome 58 ), wss:// ( since Chrome 58 ), urn: ( since Chrome 91 ), or chrome-extension://. In addition, even certain requests with URLs using one of the above schemes are hidden. These include chrome-extension://other_extension_id where other_extension_id is not the ID of the extension to handle the request, https://www.google.com/chrome, and other sensitive requests core to browser functionality. besides synchronous XMLHttpRequests from your extension are hidden from blocking event handlers in orderliness to prevent deadlocks. note that for some of the supported schemes the set of available events might be limited due to the nature of the match protocol. For exercise, for the file : scheme, only onBeforeRequest, onResponseStarted, onCompleted, and onErrorOccurred may be dispatched. Starting from Chrome 58, the webRequest API supports intercepting the WebSocket handshake request. Since the handshake is done by means of an HTTP upgrade request, its run fits into HTTP-oriented webRequest model. note that the API does not intercept :

  • Individual messages sent over an established WebSocket connection.
  • WebSocket closing connection.

Redirects are not supported for WebSocket requests. Starting from Chrome 72, an annex will be able to intercept a request only if it has host permissions to both the requested URL and the request instigator. As the pursue sections explain, events in the world wide web request API use request IDs, and you can optionally specify filters and extra information when you register event listeners .

# Request IDs

Each request is identified by a request ID. This ID is singular within a browser session and the context of an propagation. It remains constant during the the animation cycle of a request and can be used to match events for the lapp request. note that several HTTP requests are mapped to one web request in font of HTTP redirection or HTTP authentication .

# Registering event listeners

To register an event hearer for a network request, you use a variation on the common addListener() function. In addition to specifying a recall function, you have to specify a trickle argument and you may specify an optional excess information argument. The three arguments to the web request API ‘s addListener() have the watch definitions :

 volt-ampere  recall  =  affair ( details )  { ... } ;
volt-ampere filter = { ... } ;
volt-ampere opt_extraInfoSpec = [ ... ] ;

here ‘s an model of listening for the onBeforeRequest event :

chrome .webRequest .onBeforeRequest. addListener (
callback, filter, opt_extraInfoSpec ) ;

Each addListener() call takes a mandatary recall officiate as the first parameter. This recall routine is passed a dictionary incorporate data about the stream URL request. The information in this dictionary depends on the specific event type vitamin a well as the capacity of opt_extraInfoSpec. If the optional opt_extraInfoSpec array contains the bowed stringed instrument 'blocking' ( only allowed for specific events ), the recall function is handled synchronously. That means that the request is blocked until the recall routine returns. In this case, the recall can return a webRequest.BlockingResponse that determines the promote life cycle of the request. Depending on the context, this reaction allows cancelling or redirecting a request ( onBeforeRequest ), cancelling a request or modifying headers ( onBeforeSendHeaders, onHeadersReceived ), and cancelling a request or providing authentication credentials ( onAuthRequired ). If the optional opt_extraInfoSpec align contains the chain 'asyncBlocking' alternatively ( alone allowed for onAuthRequired ), the extension can generate the webRequest.BlockingResponse asynchronously. The webRequest.RequestFilter filter allows limiting the requests for which events are triggered in versatile dimensions :

URLs
URL patterns such as *://www.google.com/foo*bar.
Types
Request types such as main_frame (a document that is loaded for a top-level frame), sub_frame (a document that is loaded for an embedded frame), and image (an image on a web site). See webRequest.RequestFilter.
Tab ID
The identifier for one tab.
Window ID
The identifier for a window.

Depending on the event character, you can specify strings in opt_extraInfoSpec to ask for extra information about the request. This is used to provide detail information on request ‘s data only if explicitly requested .

# Implementation details

respective implementation details can be important to understand when developing an extension that uses the world wide web request API :

# Conflict resolution

In the current execution of the web request API, a request is considered as cancel if at least one extension instructs to cancel the request. If an annex cancels a request, all extensions are notified by an onErrorOccurred event. only one elongation is allowed to redirect a request or modify a header at a time. If more than one extension attempts to modify the request, the most recently installed extension wins and all others are ignored. An annex is not notified if its direction to modify or redirect has been ignored. Chrome employs two caches—an on-disk hoard and a identical flying in-memory cache. The life of an in-memory hoard is attached to the life of a picture march, which approximately corresponds to a pill. Requests that are answered from the in-memory cache are inconspicuous to the web request API. If a request animal trainer changes its behavior ( for example, the behavior according to which requests are blocked ), a childlike page review might not respect this transfer behavior. To make certain the behavior change goes through, call handlerBehaviorChanged() to flush the in-memory cache. But do n’t do it much ; flushing the cache is a identical expensive operation. You do n’t need to call handlerBehaviorChanged() after registering or unregistering an event hearer. The timestamp property of web request events is only guaranteed to be internally coherent. Comparing one event to another event will give you the correct stolon between them, but comparing them to the current time inside the extension ( via (new Date()).getTime(), for example ) might give unexpected results .

# Error handling

If you try to register an event with invalid arguments, then a JavaScript mistake will be thrown, and the event coach will not be registered. If an error is thrown while an consequence is handled, or if an event handler returns an invalid freeze response, an error message is logged to your extension ‘s console and the coach is ignored for that request. The follow example illustrates how to block all requests to www.evil.com :

chrome .webRequest .onBeforeRequest. addListener (
affair ( details ) {
return {cancel : details .url. indexOf ( `` : //www.evil.com/ '' ) ! = - 1 } ;
} ,
{urls : [ `` " ] } ,
[ `` stop '' ]
) ;

As this affair uses a block event coach, it requires the “ webRequest ” deoxyadenosine monophosphate well as the “ webRequestBlocking ” permission in the manifest file. The following exercise achieves the same goal in a more effective way because requests that are not targeted to www.evil.com do not need to be passed to the extension :

chrome .webRequest .onBeforeRequest. addListener (
routine ( details ) { return {cancel : true } ; } ,
{urls : [ `` * : //www.evil.com/* '' ] } ,
[ `` barricade '' ]
) ;

The following case illustrates how to delete the User-Agent header from all requests :

chrome .webRequest .onBeforeSendHeaders. addListener (
affair ( details ) {
for ( volt-ampere i = 0 ; i < details .requestHeaders .length ; ++i ) {
if (details .requestHeaders [i ] .name === 'User-Agent ' ) {
details .requestHeaders. lap joint (i, 1 ) ;
break ;
}
}
return {requestHeaders : details .requestHeaders } ;
} ,
{urls : [ `` " ] } ,
[ `` freeze '', `` requestHeaders '' ]
) ;

For more example code, see the web request samples .

Leave a Reply

Your email address will not be published.