Using HTML5 Blobs to Cache Raw Files

Caching has become an issue with Atlas because links provided by the extension would only be valid for a few minutes before they expired. The solution? HTML5‘s revised blobs as defined in the File API spec. To allow the user to download the song after the link has expired, I cache the song in memory by using an XMLHttpRequest to grab the raw file as an ArrayBuffer and then convert that into a blob, which I can now access using a URL generated by using window.URL.createObjectUrl(blob). Here it is in action:


var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");"GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4  && xhr.status == 200){
    var resp = xhr.response;
    var blob = new Blob([resp]);
    var url = window.URL.createObjectURL(blob);


I can now send this url along with all associated meta data from the song to the download page:


tracklist.push({‘title‘ : xhr.title, ‘artist‘ : xhr.artist, ‘album‘ : xhr.album, ‘url‘ : url, ‘source‘ : xhr.source, ‘duration‘ : 0});
localStorage.tracklist = JSON.stringify(tracklist);
Then when the user clicks the download button, the following function will be called to trigger a download:


function downloadSong(song, url){
  // Create hidden download hyperlink
  var downloadFile = document.createElementNS("", "a");
  downloadFile.href = url; = song + ".mp3";
  // Create mouse click event 
  var event = document.createEvent("MouseEvents");
    "click", true, false, self, 0, 0, 0, 0, 0
    , false, false, false, false, 0, null
  // Trigger mouse click event on download hyperlink
  catch(exc){ console.log(exc);}

© 2012 Franz Payer, All Rights Reserved