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:


background.js

var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
xhr.open("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);
    console.log(url)
  }
};
xhr.send(null)

Console

blob:chrome-extension%3A//gipfjjchkejmlohcbhiefofhmhlhcoce/81fd137d-b47d-4125-8dfb-dac8e8a2e92d
I can now send this url along with all associated meta data from the song to the download page:

background.js

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:

menu.js

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


© 2012 Franz Payer, All Rights Reserved