Monday, April 18, 2016

Catching net::ERR_NAME_NOT_RESOLVED for fixing bad img links

Leave a Comment

I have a blog going for over 10 years & I would like to run a piece of Javascript on it that catches broken links. I was using:

function trackError(e) {     var ie = window.event || {};     var errMsg = e.message || ie.errorMessage || "404 error on " + window.location;     var errSrc = (e.filename || ie.errorUrl) + ': ' + (e.lineno || ie.errorLine);     mailme([errMsg, errSrc]); }  // Triggering an error in the console: // You have to use something like setTimeout(function() { notThere(); }, 0); window.addEventListener('error', trackError, true); 

But that's not catching the error in a useful way. What was broken, on which line etc.

Error loading an image

JSON.stringify of the error object results just in "{"isTrusted":true}" which is useless. I noticed in Chrome there is e.path, but not in Firefox. Is there a way in Javascript to log useful information about broken image links or I need to file bugs on browser engines?

2 Answers

Answers 1

It's working. It will not stop the error from showing in Chrome in your console but it's working. Don't be bothered by the fact that you still SEE the error in Chrome. Your code is executing and you can write your mailme function and it will execute. I used the following to test:

index.html

<html> <head>     <script src="./app.js"></script> </head> <body>     <img src="http://pictures.natalian.org/screenies/2004/sep/29/13:23:00/"> </body> </html> 

app.js

var mailme = function() {     console.log('Caught!'); }  window.addEventListener('error', function(e) {     var ie = window.event || {};     var errMsg = e.message || ie.errorMessage || "404 error on " + window.location;     var errSrc = (e.filename || ie.errorUrl) + ': ' + (e.lineno || ie.errorLine);     mailme([errMsg, errSrc]); }, true); 

output (Chrome)

output (Firefox)

Answers 2

https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onerror:

When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element, that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a single capturing window.addEventListener.

(Highlighting by me.)

So it might simply be an issue of what it says there for Firefox, is not the same for Chrome.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment