在我的网页中,我有一个图像标记,其源通过https连接从api获取图像,有时此请求会失败并重定向到http连接上的错误图像,从而向用户发出警告,某些网页部分处于不安全连接上。有没有办法防止浏览器使用不安全的链接,或者以某种方式将其更改为使用javascript通过https下载。
<img src="https://example.com/image_320x240.png"/>
api并不总是准备好图像,因此它将重定向到
<img src="http://example.com/error_320x240.png"/>
错误图片也可以在https上找到,但我不知道如何让浏览器使用js或在下载图片之前检查url。
您可以尝试通过JavaScript:加载图像来解决问题
var img = new Image();
img.onerror = function(e) {
// Do something on error. Load other image?
}
img.onload = function() {
if (this.src.match(/https:/)) {
document.getElementById('foo').src = this.src;
} else {
this.src = this.src.replace('http:', 'https:');
}
};
img.src = 'https://example.com/image_320x240.png';
html中的图像元素看起来像:
<img src="" alt="" id="foo" />
代码所做的是通过javascript加载图像。如果加载了图像,则会检查加载图像的url。如果url是安全的,那么通过将其分配给DOM中的元素来显示图像。如果没有,则将不安全的url更改为安全的url,并加载新url中的图像。
我希望这能进一步帮助你。
如果上面的图像还没有准备好,你能提供自己的错误图像吗?
也许是这样的:
function populateImage(url, element) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onreadystatechange = function() {
if (req.readyState === 4) {
var img = document.createElement('img')
if (req.status === 200) {
img.src = url;
} else {
img.src = 'https://path.to.my.errorImage';
}
element.appendChild(img);
}
};
req.send();
}
<p id='placeholder'></p>
populateImage('https://exmple.com/320x240.png',document.getElementById('placeholder'));