Javascript: Which parameters are there for the onerror event with image objects? How to get additional details on an error related to an image?

懵懂的女人 提交于 2019-12-05 01:59:25

AFAIK the image.onerror handler will receive a single Event parameter that doesn't contain any info on the cause of the error.

If you want to trap errors on a normal HTML img element (rather than dynamically creating one via the DOM), this seems to work well:

 <img src="http://yourdomain/site/badimage.png" 
      onerror="javascript:imageErrorHandler.call(this, event);"/>

Note that the .call(this, event) syntax is important so you have access to the this and event objects in your error handler.

Then you can define an image error handler like the following. (Make sure it is defined before the img element to avoid race conditions.) Assuming you have jQuery wired up:

 function imageErrorHandler(evt) {
    var $e = $(this);
    var src = $e.attr("src");
    console.log("Image URL '" + src + "' is invalid.");
 };

Tested this in Chrome. Have not tried other browsers.

Image.onerror comes with a handler rather than error message, url, ...

So, the first item in the list of arguments is an event.

If you try your code with

image.onerror(errorMsg, url, lineNumber, column, errorObj) {
  console.log(errorMsg);
  console.log(url)
}

you should get an event for the first log and undefined for the second.

I haven't been able to locate any legit reference as to what comes with the onerous handler for an Image object. But looks like it is mostly used to flag the error to the user rather than the developer.

The exact results might depend a bit on the browser you're using, but you'll get one parameter only, the event. I guess the source you found was out-dated. I hacked this little JSFiddle http://jsfiddle.net/Lsag7pt6/ so you can try it yourself. Just comment in and out the correct and the "wrong" URL at the bottom of the script, open your JavaScript console (F12) and you'll see a print-out of the event with all it's attributes and values.

For reference, for the correct URL I get:

Event {isTrusted: true, type: "load", target: img, currentTarget: img, eventPhase: 2…}
bubbles:false
cancelBubble:false
cancelable:false
composed:false
currentTarget:null
defaultPrevented:false
eventPhase:0
isTrusted:true
path:Array(6)
returnValue:true
srcElement:null
target:null
timeStamp:2109.725
type:"load"

Otherwise

Event {isTrusted: true, type: "error", target: img, currentTarget: img, eventPhase: 2…}
bubbles:false
cancelBubble:false
cancelable:false
composed:false
currentTarget:null
defaultPrevented:false
eventPhase:0
isTrusted:true
path:Array(7)
returnValue:true
srcElement:img
target:img
timeStamp:1189.805
type:"error"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!