When is it safe to call URL.revokeObjectURL?

Okay, well, following @adeneo’s advice I tested this

$('#test').on('change', function(e) {
	var newImg = document.createElement("img");
    var url = URL.createObjectURL( e.target.files[0] )
    console.log(url);
    
    newImg.src = url;
    URL.revokeObjectURL(url);
    document.body.appendChild(newImg);
    console.log(url);
});

$('#test3').on('change', function(e) {
	var newImg = document.createElement("img");
    var url = URL.createObjectURL( e.target.files[0] )
    console.log(url);
    
    newImg.src = url;
    newImg.onload = function() {
    	URL.revokeObjectURL(url);
    	document.body.appendChild(newImg);
      var i = new Image();
      i.src=  newImg.src;
      document.body.appendChild(i);
      setTimeout(function() {
        var g = new Image();
        g.src = newImg.src;
        document.body.appendChild(g);
      }, 3000);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>test revoke before use</p>
<input type="file" id="test"/>
<br />
<br />
<br />
<p>test use revoke use</p>
<input type="file" id="test3" />

At least in Firefox, once URL.revokeObjectURL is called the URL can no longer be used, even though other things are accessing it.

So both #1 and #2 in the question fail and, even though in #2 newImg.src still has the URL that URL won’t work anywhere else once URL.revokeObjectURL has been called.

Leave a Comment

Hata!: SQLSTATE[08004] [1040] Too many connections