pulse00
pulse00

Reputation: 1314

Send custom HTTP request header with HTML5 audio tag

Is it possible to send custom HTTP request headers using the HTML5 audio tag? I'm especially interested in sending a HTTP Range header, so the webserver will only stream parts of an mp3 file. I couldn't find a way to do that in the audio tag api.

Upvotes: 13

Views: 9772

Answers (3)

Kelvin Dealca
Kelvin Dealca

Reputation: 305

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.

Upvotes: 11

Kaiido
Kaiido

Reputation: 136996

To answer the broad question... that will depend on what kind of request exactly.

What you want[ed] to do is actually very possible. You can simply add a #t=start[,end] Media Fragment to any media url, and the browser will know it will have to only play from these timestamps:

<!-- only from 23s to 27s -->
<audio src="https://dl.dropboxusercontent.com/s/8c9m92u1euqnkaz/GershwinWhiteman-RhapsodyInBluePart1.mp3#t=23,27" controls></audio>

And since I came from the future a question that did ask about sending authorization along with the media request, here is a link to some docs about the crossOrigin attribute, which will also make your HTTP request with "custom headers".

Upvotes: -2

Michael Kariv
Michael Kariv

Reputation: 1453

Not according to the spec, you can't. Audio tag is actually very inflexible.

Upvotes: 6

Related Questions