I have several iframes pointing to external websites on my page. In case those services are interrupted or changed, I would like to hide those iframes instead of displaying an error message on my page.
Is there any way to find out in Javascript if the iframe has been loaded correctly?
I added a class to hide the iframe and then remove it with jQuery when the iframe is ready, like this:
$('#widget').ready(function () {
$('#widget').removeClass('hidden');
});
It still removes the hidden class when I put an invalid URL in the iframe src, showing the error iframe.
My questions are two:
- How can I make the function just run if the iframe has been loaded correctly?
- Instead of using $('#widget').ready, I would like to use $('iframe').ready to target all iframes at once; if I do so, how to refer to the specific iframe loaded, inside the function?
Thanks!
Your question can be boiled down to :
how can I check if an URL exists and the website is alive from Javascript ?
The answer is splitted in:
For internal URLs, use AJAX and check the response code: if it's 2xx
or 3xx
(eg 200 or 302), it's fine. If it's 4xx
or 5xx
(eg. 404 or 500) it's bad. Read more on a similar answer.
For external URLs, you can't do it due to a security measure called same-origin policy.
Since it seems you are pointing to external URLs, here is my suggestion:
Create a server-side component (a Servlet, a RESTful WebService, a Struts2 action, etc... whatever you prefer, according to the server side technology you are using) that perform the check for you, and return a streamed response with the data (if any) and the HTTP response code that you can check for errors. Then from the <iframe>
s call your component URL.
You probably can't do exactly what you want using Javascript, you need server-side things, PHP for instance.
However, here are some helpful places to look for more info:
You can run code after an iframe loads with this JQuery function:
$('#myIframe').load(function(){
//your code (will be called once iframe is done loading)
});
Look at this Stack Overflow question and answers about iframe loading.
To target the specific element inside the function, do:
$('iframe').aFunction(function() { this.doSomething(); } );
Look at this Stack Overflow question and answers about "this".