Send custom HTTP request header with HTML5 audio tag

If you’re okay not supporting older browsers like IE, you can do this now with a service worker. Intercept the fetch request in the service worker and send it onwards with the custom header. Here is a basic example of intercepting a request to Google Drive and adding the Bearer token.

self.addEventListener('fetch', function(event) {
  if(event.request.url === 'https://www.googleapis.com/drive/v3/files/fileID?alt=media') {
    event.respondWith(
        fetch(event.request.url, {
            method: "GET",
            headers: {
                "Authorization": "Bearer myBearerToken",
            },
            redirect: "follow"
        })
    );    
  }
});

Edit: 2018-11-17 – Added how this won’t work with older browsers.

Leave a Comment