N
N
number12018-08-11 01:01:05
JavaScript
number1, 2018-08-11 01:01:05

Is it possible to intercept and change the http request using Service Worker?

Is it possible with the help of Service Worker to intercept the http request and change its body or headers.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2018-08-11
@number1

One of the tasks of the Service Worker is a programmable proxy on the client side.
That is, your question "is it possible?" - I would answer yes - this is one of the main functions of the Service Worker.
But there is one thing, Service Worker only works with the domain from which its code is loaded. That is, you can intercept only requests to your domain. Moreover, this function is available only for non-cross-domain requests (those that come from the pages of their own domain). It is also worth mentioning the experimental foreignfetch event mentioned in the chrome feature summary on google developers for September "16 - it allows you to intercept calls to your domain from other people's resources, but neither mdn nor caniuse knows about it - as a result, the event potentially only works in chrome 54+.
It is also worth considering that Service Worker support is only well implemented in Chrome and Firefox. It appeared in Edge from version 17 (released with win10 April "18 update), it also appeared in safari recently (11.1 - desktop, 11.4 - iOS)
If everything suits you, then:
Read this article on mdn: https://developer. mozilla.org/ru/docs/Web/API/Serv...
Since from getting higher for your task you can only learn how to work with the fetch event (we work similarly with the foreignfetch event) and most of the examples are aimed at a programmable cache, and for request forgery you need to generate your Responce object - read this article: https://developer.mozilla.org/en-US/docs/Web/API/R... (only English) We
also read about Request:https://developer.mozilla.org/en-US/docs/Web/API/R...
The whole point will come down to something like the following Service Worker code:

self.addEventListener('fetch', event => {
  const {request} = event;
  // обрабатываем request чтоб понять, что от нас хотят
  //...
  if(/* условие, что запрос нужно подменить */) {
    event.respondWith(new Response('Hello world', /* вместо строки можно Blob или ArrayBuffer */ {
      headers: { 'Content-Type': 'text/plain' }
    }));
  } else {
    event.respondWith(fetch(request)); // если не наш случай, отправляем запрос на сервер,
    // тут так же можно заморочится с кэшем
  }
});

If some conditions are not suitable, then the only way out will be to impose our browser extension on the user ... fortunately, with the latest party policy, they can no longer be installed on the sly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question