Intercept all outgoing requests

75
April 16, 2018, at 07:14 AM

In short, is there any way to intercept all outgoing requests in a page in order to append an Authorization token to the header prior to sending the request? This includes all requests that are out of the control of the user (non-clickable ones) such as request to image sources <img src=''.../> and particularly iframes.

I found another post in SO which suggests using a service worker:

window.addEventListener('load', function() {
    navigator.serviceWorker.register('sw.js').then(function(registration) {
    console.log('Service worker registered with scope: ', registration.scope);
    }, function(err) {
    console.log('ServiceWorker registration failed: ', err);
    });
});

and then intercepting the calls in sw.js:

self.addEventListener('fetch', function(event) {
   event.respondWith(
      console.log(event.request)
   );
});

but I have not been able to get this to work for what I am after, as although I have no error in my console, the log method never hits (testing it on a single element <img src='..'/>.

Is this even possible in JavaScript?

Important Note: Please keep in mind, a query string will not handle this requirement here. As I need to intercenpt calls within an iframe as well.

READ ALSO
Display API Data in HTML for Stock/BTC Price?

Display API Data in HTML for Stock/BTC Price?

I'm trying to display the data from this api: https://blockchaininfo/q/24hrprice and display it in an HTML file using JS under the price header for the coins

68
window.location.assign goes to wrong URL

window.location.assign goes to wrong URL

I have this code - indexphp which displays login screen, and editor

63