0

If I simplify my javascript code it is like this:

I have object which has method "dwnImage" responsible to download image from some url. When I call this method I would like that result of this method tell me if image was downloaded successfully or there were some error, like img doesn't exists, wrong url. How can I do that?

GM.Log=function(){
  var imgLg=null;
  var result=0;
  var imgLoaded = function () {
    result=1;
  };
  var init = function () {
    imgLg= new Image(1,1);
    imgLg.addEventListener('load', imgLoaded(), false);
  }

  var dwnImage=function(url){
    imgLg.src=url;
    return result;
  }
  return {
    init: init
  }
}

var test=new GM.Log();
test.init();
var result=test.dwnImage("http://...");
Simon
  • 1,955
  • 5
  • 35
  • 49

1 Answers1

0

Generally speaking, you can't. The use of http:// on the final line of your code implies that you are going to bounce off the same origin policy: You can't get load events on cross-origin resources.


If that isn't the case then you need to:

  1. Pass a function and not the return value of that function to addEventListener
  2. Learn how to handle asynchronous functions
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • "Pass a function and not the return value"- i don't know what exactly do you mean since I pass a function. Can you correct this sample code to show what you mean? Thanks. – Simon Nov 23 '16 at 10:12
  • @Simon — There's a link to a question which details that specific problem. Click it. – Quentin Nov 23 '16 at 10:13
  • Example is clear to me.But if i add this: imgLg.addEventListener('load', imgLoaded, false); imgLoaded function is never executed(I put alert inside to test). Do you know why? – Simon Nov 23 '16 at 10:47
  • @Simon — Probably for the reasons I described in the first paragraph of the answer. – Quentin Nov 23 '16 at 10:48
  • Ok, if img doesn't exists or is other origin how can I catch result as 0 and when everything ok, the result should be 1. https://codepen.io/simon1/pen/MbmXpW – Simon Nov 23 '16 at 11:09