问题
The following snippet will replace the PNG image with GIF image if the link is broken or does not exist. I tried to apply this on an iframe but it does not seems to work. Is this even possible?
<html>
<body>
<iframe src="index1.html" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';"> </iframe>
<img src="test.png" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';" />
</body>
</html>
Would greatly appreciate response. Thanks in advance! :)
回答1:
The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).
The iframe content is not a file, thus, onerror won't be triggered. You can use JS to check if you get an HTTP success response (200).
var myRequest = new Request('index1.html');
fetch(myRequest).then(function(response) {
console.log(response.status); // returns 200
}).catch(function(error) {
document.getElementById("iframe-id").src = "/your/file/path/here/somePage.html";
});
<iframe id="iframe-id" src="index1.html"> </iframe>
<img src="test.png" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';" />
来源:https://stackoverflow.com/questions/52639526/using-onerror-on-an-iframe