Basically I have an iframe loaded that is accessed from the parent whenever it trigger the onload event. It works fine but I'm getting errors when the contents of the iframe are no longer on the same domain, which is to be expected.
Only thing is, I'd like to suppress these errors. Unfortunately a try/catch doesn't catch this exception and trying to access any of these properties to validate them produces the same error again, thus defeating the purpose.
Is there a reliable way for me to simply check if the iframe contents are accessible without producing any error messages?
Thanks
Edit:
For the sake of context and not having people answer with irrelevant comments; I am writing a small script that auto resizes the iframe on the parent page based on the height of the iframes document. When a user clicks a link inside the iframe that points outside the domain I obviously won't be able to detect the height of the page, but I'd prefer not to trigger any errors in the console and instead handle the exception gracefully.
I am aware that there are workarounds available, I am simply trying to educate myself by figuring out if there is a graceful way to handle these kinds of cases, rather than just resorting to an ugly workaround.
Try this:
var $frame = $("#frameId"); // swap with the id of the iframe
try {
var canAccess = $frame.contents();
if(!!canAccess) {
// same domain yay you have access
// do your thing here
}
}
catch( e ) {
// bummer can't do much with it
return false;
}
EDIT: add a try and catch, no error will return false.
The jQuery approach can also be done with regular JS:
function iframe_accessible(theiframe) {
var thedoc, debug=true;
try{
thedoc = (theiframe.contentWindow || theiframe.contentDocument);
if (thedoc.document)
thedoc = thedoc.document;
if (debug)
console.log('Accessible');
return true;
}
catch(err) {
if (debug)
console.log("Not accessible because of\n" + err);
return false;
}
}
var elm = document.querySelector('iframe'); // If it exists, of course
console.log(iframe_accessible(elm));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With