【问题标题】:Get list of links that have thrown a 404 error after browser loads获取浏览器加载后抛出 404 错误的链接列表
【发布时间】:2013-10-25 04:43:36
【问题描述】:

我有一个加载一堆图片的页面。

一些链接指向不存在的图像,因此浏览器在尝试检索这些图像时会抛出 404。

这是一个问题的例子:

<div>01<img id="01" src="http://i.imgur.com/ydiBX0Bb.jpg" /></div><hr />
<div>02<img id="02" src="http://i.imgur.com/aObMmrWb.jpg" /></div><hr />
<div>03<img id="03" src="http://www.google.com/does_not_exist.jpg" /></div><hr />
<div>04<img id="04" src="http://www.google.com/also_does_not_exist.jpg" /></div><hr />
<div>05<img id="05" src="http://i.imgur.com/kJezbugb.jpg" /></div><hr />

还有小提琴:

http://jsfiddle.net/amv3z/

图像 1、2 和 5 都可以正常加载。图片 3 和 4 不存在。

因此,我的开发控制台会吐出以下错误:

GET http://www.google.com/does_not_exist.jpg 404 (Not Found)
GET http://www.google.com/also_does_not_exist.jpg 404 (Not Found)

我可以使用 JavaScript / jQuery 获取引发 404 错误的图像链接列表吗?

谢谢!

【问题讨论】:

  • 不。但是您可以遍历所有这些并测试它们的宽度/高度。未加载的将具有 0 的宽度/高度。
  • 您可以添加一个 onerror 事件处理程序以查看它们是否失败...反之亦然...添加一个注册成功事件的 onload 事件处理程序。
  • 采用循环图像并获取宽度/高度的方法。奇迹般有效!感谢您的帮助。

标签: javascript jquery html http http-status-code-404


【解决方案1】:

您所寻找的似乎已经在 stackoverflow 上。

Click here to see the original question.

您需要做的基本上是将任何一段代码放入 for 循环中。 如果您想这样做,您将需要一组图像源。

链接中的纯JS函数:

function resourceExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

使用链接中提到的功能的示例:

var aImageSrc = ['path/to/img/1', 'path/to/non/existant/img/2', 'path/to/other/img'];
var aErrorSrc = []; //Will be filled with non-existant images.
var imgStr = '';

for (var i = 0; i < (aImageSrc.length-1); i++) {
    if (!resourceExists(aImageSrc[i])) {
        aErrorSrc.push(aImageSrc[i]);
    } else {
        //Append image to string if it exists.
        imgStr += '<image src="'+aImageSrc[i]+'" alt="Don't forget the people with lesser visibility" />';
    }
}

//Append the string to any element you need to create
//If you want to append the image anyways even tho it does not exist,
//You could remove the else in the for-loop and just put the append line below it.

//To top it off, do a console log to display all the errors.
console.log(aErrorSrc);

注意

不要忘记从脚本中删除console.log();,因为 IE(ofc,还有什么...)有点笨,当控制台关闭时,当它遇到 console.log 时,它将停止执行从那时起的任何事情,或者根本不执行任何事情。

希望这有帮助

&dash;席德

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多