Intercepting browser requests for resources

Is there a way to load the initial script (the file at the top of the page), which then tries to intercept all other requests for resources (scripts, css, images, etc.) as the page continues to load?

The purpose of this interception is to instead serve files from the cache (localStorage, indexedDB, other) or even from a remote peer via webrtc agnostically, which does not depend on how the application / page is assembled together.

I am aware of explicit / autonomous approaches to the cache, but here I need to take the requested resource and proxy server from the selected location.

+8
source share
1 answer

.

, , , , .

, , .

, ( Ctrl+F5), , . , , .

image/js URL-, . script.js .

https://next.plnkr.co/edit/dP6wr0hB1gbXDeQs?preview

HTML

<html>
  <body>
    <h2>My intercepted page</h2>
    <script src="script.js"></script>

    <script src="jquery.js"></script>

    <div class="placeholder">a</div>
    <img src="z9t29Bk.gif">
    <img src="y2kChjZ.gif">
    <script>$(".placeholder").text("loaded jquery version:"+$.fn.jquery)</script>
  </body>
</html>

script.js

if ('serviceWorker' in navigator) { 
    var interceptorLoaded = navigator.serviceWorker.controller!=null;
    window.addEventListener('load', function() { 
      navigator.serviceWorker.register('sw.js')
      .then(function(registration){
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
          if(!interceptorLoaded){
            //refresh after interceptor was loaded but only if the interceptor was not already loaded.
            window.location=window.location.href; 
          }
      },
        function(err) { // registration failed :( 
        console.log('ServiceWorker registration failed: ', err); 
      }); 
  }); 
}       

sw.js

self.addEventListener('fetch', function(event) {
  console.log("REQUEST:", event.request.url);
  var url = event.request.url;
  if (url.endsWith("/jquery.js")) {
    event.respondWith(
      fetch('https://code.jquery.com/jquery-3.3.1.js')
    );
  }else if(url.endsWith(".jpg") || url.endsWith(".png") || url.endsWith(".gif")){ 
      event.respondWith(fetch("https://i.imgur.com/"+url.substring(url.lastIndexOf("/")+1),{
        mode: 'cors',
    }));
  }
})

Ref: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer

+3

All Articles