12

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.

5
  • 5
    Maybe it's a sign telling you not to use iframes...
    – Nahydrin
    Jan 23, 2012 at 14:35
  • 8
    Seriously? Please refrain from commenting if you have nothing to contribute.
    – Naatan
    Jan 23, 2012 at 14:38
  • Naatan, the guy's giving you an advice that I +1. You cannot have the page and frame communicate to each other or manipulate each other's content (at all; not even read it) - if their protocol and hostname don't match to the letter. That's it, and there will never be a way to make that behave differently. That's to prevent malicious guys mess with and steal from innocent people out there.
    – user191966
    Jan 30, 2012 at 14:31
  • 7
    Hari, I am well aware of that, but seeing as I am not giving you the context of my question you shouldn't make up one. In your scenario my question makes no sense, which I agree with. But it's irrelevant, I'm asking a question and all you're doing is saying "WELL, in MY scenario your question makes no sense what so ever so you should just NOT do what you're trying to do to being with". It's irrelevant. I will update my main question with context though, so as not to have to continue these types of comments.
    – Naatan
    Jan 30, 2012 at 15:25
  • while this answer is irrelevant to this question, reminding all devs "to avoid using iframes whenever possible" is a solid advice. :(
    – Uri Kutner
    Jan 14, 2021 at 16:45

8 Answers 8

5
+25

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 of onload. For example, you could add this to each page:

if (window.parent) document.addEventListener( 'load', function() {
    window.parent.postMessage( "child loaded", "/" );
}, false );

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:

var iframe = document.getElementById( 'your-iframe' );
var origin = window.location.protocol + '://' + window.location.host;
if (window.location.port != 80) origin += ':' + window.location.port;

window.addEventListener( 'message', function (event) {
    if (event.source != iframe.contentWindow
            || event.origin != origin || event.data != "child loaded")
        return;

    // do here what you used to do on the iframe's load event
}, false );

Note that the examples use the W3C/Netscape event API and thus won't work in Internet Explorer before version 9.

4

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.

2
  • It triggers the same IF statement in either case (accessible or non-accessible iframe). Oddly enough no security error though, I wonder if you're on to something here ..
    – Naatan
    Jan 30, 2012 at 14:00
  • 1
    This worked fine for me. Triggers for internal domains, ignores for external domains. No errors.
    – firewaller
    May 26, 2016 at 7:20
1

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));

0

You can get the current URL of the iframe using window.frames['frame_name'].contentWindow.location.href.

If the user has navigated away from your domain then there's no way to do it. Sorry...

More information here.

4
  • Thanks for your response. I know I can do this, but that's not my question. The problem is that I can't even "attempt" to get this information without the browser throwing permission errors at me when the iframe is serving content outside the parents domain. I want to surpress these errors, basically the way you would with a try/catch phrase, only for whatever magical reason these types of errors aren't caught with try/catch (least not in Firefox).
    – Naatan
    Jan 18, 2012 at 21:40
  • I don't think there's a way to suppress these kind of browser errors. It's the same with 404 AJAX requests.
    – Jivings
    Jan 18, 2012 at 21:51
  • @Naatan: Worst case scenario, you can schedule a setTimeout in 0 ms to workaround that.
    – Hello71
    Jan 18, 2012 at 22:16
  • 1
    @Naatan: It doesn't, but you can continue running if you schedule another one before it errors.
    – Hello71
    Jan 18, 2012 at 22:19
0

Can't you access the src attribute from the parent?

As I understand it, the iframe element belongs to the 'parent' page, whereas the window object contained with the iframe belongs to the 'child' page.

This works for me:

<html>
<head>
</head>
<body>
<iframe id="ifr" name="ifr" src="http://www.example.com"></iframe>
<input type="button" onclick="showSrc()" value="showSrc" />
<input type="button" onclick="showHref()" value="showHref" />
<script>
    var ifr = document.getElementById('ifr');
    function showSrc() {
        // no warning
        alert(ifr.src);
    }
    function showHref() {
        // warning
        alert(window.frames['ifr'].contentWindow.location.href);
    }

</script>
</body>
</html>
2
  • I can, the problem is however that one can click links inside the iframe, which would not change the src attribute on the parent.
    – Naatan
    Jan 23, 2012 at 14:47
  • @Naatan Damn. That's right. Then I don't think that there is anyway to do it without an error raised.
    – Tim
    Jan 23, 2012 at 14:55
0

Ok this is overkill, not much but a hack and maybe not possible in your situation but anyway :

You could add a javascript inclusion in all the pages from your site that tries to access the opener(the parent frame) and set a flag(a variable like bool stillOnMySite) to true.

Then

  1. Time based : The script in your website pages sets the flag every second to true, the script in your parent iframe sets the flag every second to false. Poll the iframe in a setTimeOut(xxx,1). If the flag is not true again, then the user left your site and you shouldn't poll the iframe if the flag is true, the user is still on your website you can poll the iframe.

  2. Click based : Using jquery for unobtrusive javascript, the script in your website pages monitors clickevents in all the links in the page. If a link is going outside your domain, this sets the flag in the parent iframe to false.

Of course this all theory crumbles to pieces if you can't add script in your website pages.

Alternatively, I just thought : If your iframe always start on your website, no need to modify your website pages, simply inject the n°2 solution from the parent iframe into the iframed page.

2
  • Interesting approach, and it might be worth resorting to this, though I'd have liked to develop the script in question without dependencies.
    – Naatan
    Jan 30, 2012 at 14:04
  • Using the alternate scenario, that is if your iframe always starts on your website, you can inject the onclick monitor on every link of the iframed page from the iframe parent. jQuery makes it ultra-easy but you can do it in pure javascript too. Good luck !
    – Yahel
    Jan 30, 2012 at 14:17
0

could you tell me how you set the iframe's src?
if you use javascript to change it dynamiclly,your problem is easy to be handle with.

var isXdm = false;
function setSrc(id,src){
   //detect whether src is cross domain then set the variable isXdm
   ...
}

even so,i do not think it is a good way to solve this.
hope anyone could find a better solution.

1
  • Hi Simon, the problem is not with the src attribute, I realize I can easily read this. It's about the iframe changing location once it's loaded (eg. when a user clicks a link in the loaded page).
    – Naatan
    Jan 30, 2012 at 14:03
0

How about not rendering IFRAME at all (within parent page) if its href is not pointing to the same protocol and host as the parent page? I'm possibly misunderstanding things related to whether you own both sites, or only one of them (and which one). But if you own the parent-page site, you should be able to do this, whether on the server (before IFRAME is even included), or at some point on the client (page-load/doc-load).

2
  • Hey Hari, the problem I'm having is not with the original src being loaded, but rather with people clicking links in the loaded iframe that point outside the domain. I think I will have to resort to a workaround though.
    – Naatan
    Jan 30, 2012 at 14:02
  • 1
    Hm, clicking links within an IFRAME shouldn't result in such behavior; it should work the same way as if you opened that framed page in the top window. You are either trying to talk to that IFRAME (or manipulate its content), or IFRAME has code that is referencing top window. I started sensing secrets in your question...
    – user191966
    Jan 30, 2012 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.