jeudi 16 avril 2015

How can I stream a video from a ServiceWorker?

I have a service worker that catches my page's requests (fetch event), and when the URL matches a certain pattern, it would fetch another URL and replace the response with that new content. It works perfectly for text data (JS, XML...) or binary data (e.g. images), but when it comes to video, there is a glitch.


I am using Chrome 41 on OSX.


This is the simplified code of my worker:



self.addEventListener('fetch', function(event) {
var url = event.request.url;
console.log('SW: fetch', url);
if (/\.mp4$/.test(url)) {
url = 'http://ift.tt/1yxEx6l';
var options = {
credentials: 'include',
mode: 'no-cors'
};
event.respondWith(fetch(url, options));
}
});


And this is the simplified code in my HTML page:



navigator.serviceWorker.register('sw.js').then(function(reg) {
console.info('ServiceWorker registration successful for', reg.scope);

var video = document.createElement('video');
video.src = '/video.mp4';
video.controls = true;
video.autoplay = true;
video.onerror = function(err) {
console.error('Video load fail', err);
}
video.onload = function(data) {
console.info('Video load success');
}
document.body.appendChild(video);

}).catch(function(err) {
console.error('ServiceWorker registration failed:', err);
});


The first time you load the page, the worker installs, so the video request is not caught, thus failing. But when you reload the page (without cleaning the cache), it is successfully caught, and the worker successfully loads the video (HTTP 200 in its inspector), but for some reason, the main page throws a net::ERR_FAILED. Maybe because I need to stream it?


Aucun commentaire:

Enregistrer un commentaire