Alter the prototype of an image tag?

dom, javascript

Solution

window.addEventListener("error", function(e) {
    if ( e && e.target && e.target.nodeName && e.target.nodeName.toLowerCase() == "img" ) {
        alert( 'Bad image src: ' + e.target.src);
    }
}, true);

See: http://jsfiddle.net/Vudsm/

Problem

I am trying to write a library that would do the following. When the library is included in the head, it would alter the HTMLImageElement prototype such that any image tag that the user happened to use in their HTML or that they create dynamically in javascript would have a default onerror function that is defined by my library. The result of this would be that if any of the users images failed to load because they pointed to a bad url my library would handle it in a graceful way. I am trying the following just as an experiment, ``` var img = document.createElement('img'); img.__proto__.onerror = function() { alert('hi'); }; document.body.innerHTML = '<img id="foo" src="bar.png"/>' ``` where the file bar.png does not exist and it does not work. However if I just do something like ``` document.body.innerHTML = '<img id="foo" src="bar.png" ' + 'onerror="this.src = MODIT.getImage(\'blackTile\').src;"/>'; ``` that works fine. Here MODIT.getImage() is a function that returns an image element. You can play with this code here: https://mod.it/ciR_BxqJ/ Is what I'm trying to do possible? Alternatively is there a way to globally catch all 403 GET errors and handle them with javascript in some way? Thanks!

Original source

Related problems