Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using onerror on an iframe

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! :)

like image 697
Renz C. Gohing Avatar asked Oct 25 '25 17:10

Renz C. Gohing


1 Answers

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';" />
like image 69
Itay Gal Avatar answered Oct 27 '25 06:10

Itay Gal