Catching net::ERR_NAME_NOT_RESOLVED for fixing bad img links

怎甘沉沦 提交于 2020-12-29 09:12:02

问题


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.

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?


回答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)




回答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.



来源:https://stackoverflow.com/questions/36512573/catching-neterr-name-not-resolved-for-fixing-bad-img-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!