Using onerror on an iframe

风流意气都作罢 提交于 2021-01-01 06:39:33

问题


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

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