aboutsummaryrefslogtreecommitdiff
path: root/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html
blob: fef2c0534f2e9a3d5d8edeb615cec38b143bae1e (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
156
157
158
159
160
161
---
title: Interceptar Pedidos HTTP
slug: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests
tags:
  - Add-ons
  - Como-fazer
  - Extensões
  - ExtensõesWeb
translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests
original_slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP
---
<div>{{AddonSidebar}}</div>

<p>Para interceptar pedidos HTTP,  use a {{WebExtAPIRef("webRequest")}} API. Esta API permite que você adicione ouvintes para várias etapas ao fazer uma solicitação HTTP. Nos ouvintes, você pode:</p>

<ul>
 <li>obter acesso para solicitar cabeçalhos e corpos e cabeçalhos de resposta.</li>
 <li>pedidos de cancelamento e redirecionamento</li>
 <li>modificar pedidos e cabeçalhos de resposta</li>
</ul>

<p>Neste articulo nós vamos dar uma olhada a tres usos diferentes para o modulo <code>webRequest</code>:</p>

<ul>
 <li>Logar pedidos URLs quando eles são feitos.</li>
 <li>Redirecionar pedidos.</li>
 <li>Modificar cabeçalhos de pedidos.</li>
</ul>

<h2 id="Loggar_pedidos_URLs">Loggar pedidos URLs</h2>

<p>Crie um diretorio chamado "requests". Nesse diretorio crie um ficheiro chamado "manifest.json" com o seguinte conteudo:</p>

<pre class="brush: json">{
  "description": "Demonstração webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",

  "permissions": [
    "webRequest",
    "&lt;all_urls&gt;"
  ],

  "background": {
    "scripts": ["background.js"]
  }
}</pre>

<p>De seguida, crie um ficheiro chamado "background.js" com o seguinte conteudo:</p>

<pre class="brush: js">function logURL(requestDetails) {
  console.log("A carregar: " + requestDetails.url);
}

browser.webRequest.onBeforeRequest.addListener(
  logURL,
  {urls: ["&lt;all_urls&gt;"]}
);

</pre>

<p>Here we use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the <code>logURL()</code> function just before starting the request. The <code>logURL()</code> function grabs the URL of the request from the event object and logs it to the browser console. The <code>{urls: ["&lt;all_urls&gt;"]}</code> <a href="/en-US/Add-ons/WebExtensions/Match_patterns">pattern</a> means we will intercept HTTP requests to all URLs.</p>

<p>To test it out, <a href="/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox">install the extension</a>, <a href="/en-US/docs/Tools/Browser_Console">open the Browser Console</a>, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:</p>

<p>{{EmbedYouTube("X3rMgkRkB1Q")}}</p>

<h2 id="Redirecting_requests">Redirecting requests</h2>

<p>Now let's use <code>webRequest</code> to redirect HTTP requests. First, replace manifest.json with this:</p>

<pre class="brush: json">{

  "description": "Demonstrating webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",

  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "https://developer.mozilla.org/",
    "https://mdn.mozillademos.org/"
  ],

  "background": {
    "scripts": ["background.js"]
  }

}</pre>

<p>The only change here is to add the <code>"webRequestBlocking"</code> <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permission</a></code>. We need to ask for this extra permission whenever we are actively modifying a request.</p>

<p>Next, replace "background.js" with this:</p>

<pre class="brush: js">var pattern = "https://mdn.mozillademos.org/*";

function redirect(requestDetails) {
  console.log("Redirecting: " + requestDetails.url);
  return {
    redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
  };
}

browser.webRequest.onBeforeRequest.addListener(
  redirect,
  {urls:[pattern], types:["image"]},
  ["blocking"]
);</pre>

<p>Again, we use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function will replace the target URL with the <code>redirectUrl</code> specified in the function.</p>

<p>This time we are not intercepting every request: the <code>{urls:[pattern], types:["image"]}</code> option specifies that we should only intercept requests (1) to URLs residing under "https://mdn.mozillademos.org/" (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this.</p>

<p>Also note that we're passing an option called <code>"blocking"</code>: we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on <code>"blocking"</code>.</p>

<p>To test it out, open a page on MDN that contains a lot of images (for example <a href="https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor">https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor</a>), <a href="/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox#Reloading_a_temporary_add-on">reload the extension</a>, and then reload the MDN page:</p>

<p>{{EmbedYouTube("ix5RrXGr0wA")}}</p>

<h2 id="Modifying_request_headers">Modifying request headers</h2>

<p>Finally we'll use <code>webRequest</code> to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under http://useragentstring.com/".</p>

<p>The "manifest.json" can stay the same as in the previous example.</p>

<p>Replace "background.js" with code like this:</p>

<pre class="brush: js">var targetPage = "http://useragentstring.com/*";

var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";

function rewriteUserAgentHeader(e) {
  for (var header of e.requestHeaders) {
    if (header.name.toLowerCase() == "user-agent") {
      header.value = ua;
    }
  }
  return {requestHeaders: e.requestHeaders};
}

browser.webRequest.onBeforeSendHeaders.addListener(
  rewriteUserAgentHeader,
  {urls: [targetPage]},
  ["blocking", "requestHeaders"]
);</pre>

<p>Here we use the {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} event listener to run a function just before the request headers are sent.</p>

<p>The listener function will be called only for requests to URLs matching the <code>targetPage</code> <a href="/en-US/Add-ons/WebExtensions/Match_patterns">pattern</a>. Also note that we've again passed <code>"blocking"</code> as an option. We've also passed <code>"requestHeaders"</code>, which means that the listener will be passed an array containing the request headers that we expect to send. See {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} for more information on these options.</p>

<p>The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the <code>ua</code> variable, and returns the modified array. This modified array will now be sent to the server.</p>

<p>To test it out, open <a href="http://useragentstring.com/">useragentstring.com</a> and check that it identifies the browser as Firefox. Then reload the extension, reload <a href="http://useragentstring.com/">useragentstring.com</a>, and check that Firefox is now identified as Opera:</p>

<p>{{EmbedYouTube("SrSNS1-FIx0")}}</p>

<h2 id="Learn_more">Learn more</h2>

<p>To learn about all the things you can do with the <code>webRequest</code> API, see its <a href="/en-US/Add-ons/WebExtensions/API/WebRequest">reference documentation</a>.</p>