JSFiddle - React, Tailwind, and code Playground
HTML
<h2>Blob.url proposal</h2>
<div id="description">Description: This is a demonstration of simplifying the <a href="http://dev.w3.org/2006/webapi/FileAPI/#creating-revoking" target="_blank"><code>window.URL.createObjectURL</code></a> interface to <code>Blob.url</code>. In the process we make Blob URI creation less verbose, keep the same functionality as provided by the existing method by making one-time Blob URI creation the default and make the creation of Blob URIs object-centric around the originating Blob object.</div>
<input type="file">
<div id="instructions">Instructions: Select a file from your file system using the control above. We'll then request <code>Blob.url</code> three (3) times and display the one-time only Blob URI output for each call below.</div>
<div id="debug"></div>
CSS
* {
padding: 10px;
}
h2 {
color: #000;
font-size: 24px;
font-weight: bold;
}
#description, #instructions, #debug {
color: #333;
font-size: 14px;
padding-top: 10px;
padding-bottom: 10px;
}
JavaScript
/*
* Blob.url shortcut shim
*
* Author: Rich Tibbett <rich.tibbett@gmail.com>
*/
(function() {
if(Blob && Blob.prototype && !Blob.prototype.url) {
var _url = null;
var urlBuilder = window.webkitURL || window.msURL || window.oURL || window.URL || null;
Object.defineProperty( Blob.prototype, "url", {
get: function() {
if(!urlBuilder) throw new Error("Blob URI creation not supported in your browser");
try {
// Always create a one-time only Blob URI
_url = urlBuilder.createObjectURL( this, { oneTimeOnly: true } );
} catch(e) {
try {
// Create a standard Blob URI (though the principle here is that Blob.url SHOULD always return
// a one-time only Blob URI as above)
_url = urlBuilder.createObjectURL( this );
} catch(e) {
throw new Error("Blob URI creation not supported in your browser");
}
}
return _url;
},
set: function(value){ return _url; }, // non-settable
enumerable : false,
configurable : false
});
}
})();
/*
* *** DEMO ***
*/
window.addEventListener('load', function(e) {
var fileEl = document.getElementsByTagName('input')[0],
debugEl = document.getElementById('debug');
function logOutput( str ) {
debugEl.innerHTML += str + "<br />";
console.log( str );
};
fileEl.addEventListener('change', function( e ) {
var file = fileEl.files[0];
if(!file) return;
// Should write three _one-time only_ Blob URIs for file out to the console
logOutput(file.url);
logOutput(file.url);
logOutput(file.url);
}, true);
}, true);