如何检测请求的图像是否没有错误(403 禁止访问)



我有一个脚本,它每300毫秒从一个源加载一个图像,但有时会返回403 Forbidden响应。在这种情况下,图像源变为空白,所以我想以某种方式检查图像是否有200的响应,然后更新我的图像元素。我怎么能做到呢?

这是我的代码

<body>
<!-- Live view -->
<img class="screenshot" src="screenshot.jpg">
<script>
setInterval(() => {
// Sometimes I get back a 403 forbidden
document.querySelector('.screenshot').src = 'http://192.168.1.150:80/screen/screenshot.jpg?id=' + Math.random(0, 10000)
}, 300)
</script>
</body>

我希望能够做一些类似的事情

if (status == 200) {
document.querySelector('.screenshot').src = 'http://192.168.1.150:80/screen/screenshot.jpg?id=' + Math.random(0, 10000)
} else {
// Do nothing, keep the old image
}

试试这个

const imgTag = document.querySelector('.screenshot');
const img = new Image()
img.addEventListener("load", function() {
imgTag.src = this.src;
setTimeout(reload, 1000)
})
img.addEventListener("error", function() {
setTimeout(reload, 1000)
})
const reload = () => {
img.src = 'https://picsum.photos/seed/picsum/200/' +Math.floor(Math.random() * (300 - 100 + 1) + 100)
};
reload()
<img class="screenshot" src="" />

最新更新