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.
If you can add a little JavaScript to all of the pages from your domain you’d like to load in the iframe you could use
window.postMessage, which is exempt from the Same Origin Policy. Probably the simplest way would be to have the child window post a message to the parent when it loads and use that instead ofonload. For example, you could add this to each page:That will post a message to the parent window whenever the page is loaded in a frame with the same origin. You would then listen for it like this:
Note that the examples use the W3C/Netscape event API and thus won’t work in Internet Explorer before version 9.