0

I try to use blob to show image in website but how I can get URL outside onload to return it in function?

var xhr = new XMLHttpRequest();
xhr.open("GET", "//fiddle.jshell.net/img/logo.png", true);
xhr.responseType = "arraybuffer";

xhr.onload = function(e) {
    var arrayBufferView = new Uint8Array(this.response);
    var blob = new Blob([arrayBufferView]);
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL(blob);
    //window.URL.revokeObjectURL(imageUrl);
};

xhr.send();

krlzlx
  • 5,752
  • 14
  • 47
  • 55
Ashkan
  • 1
  • 1
  • 3
    You need to know [How to return a response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jaromanda X Jan 14 '17 at 09:32
  • + you don't need to require an arraybuffer if what you want is a blob, XHR also as a `'blob'` responseType. – Kaiido Jan 16 '17 at 11:32

1 Answers1

0

if you use imageUrl=urlCreator.createObjectURL(blob); instead var imageUrl=urlCreator.createObjectURL(blob); you will put your variable in global scope and be able to access outside the function.

function yo(lo) {
window.onload=function(e){
lo("give me shiny gold");
}}


yo(function(work) {
alert(work);
});
defo
  • 7
  • 4
  • then there will be the inevitable "how do I return a value from an asynchronous function" question :p – Jaromanda X Jan 14 '17 at 09:31
  • Give me that shiny gold I need to put a bounty on my question. Anyone want to bother with Ratchet websocket that loss connection only on Windows 10. =) – defo Jan 14 '17 at 09:51