Skip to content Skip to sidebar Skip to footer

Why Can't An Iframe Set Its Parent's Location.hash?

I have a window containing an iframe, containing an iframe, like so: +---------------+ | Top | | +-----------+ | | | Middle | | | | +-------+ | | | | | Inner | | | | |

Solution 1:

Parent frames can set children's iframe 'src' attribute (here with jquery) using:

$("#iframeWindow").attr('src', "http://<CHILD URL>/#hello");

Children iframes can set parent window's href (address bar content) using:

window.top.location.href = "http://<PARENT URL>/#hello"

and in the parent and/or child, you need to poll for changes,

var last = "";
setInterval(function() {
    if(last == window.location.href) return;
    last = window.location.href;

    //do stuff with 'window.location.hash'
}, 1000);

note, it would be nice if you could

window.top.location.href = window.top.location.href + "#hello"

but reading of location object (href and hash) is not allowed

tested on 3rd Nov 11, on chrome, ie6/7/9, firefox 3.6/4

edit1: can put a demo live if people would like

edit2: http://dl.dropboxusercontent.com/u/14376395/html/xdomain.html :)

edit3: beware: if you're using this method, make sure you have control over all iframe'd pages otherwise nefarious 3rd party sites could potentially control yours using hash tags

edit4: better solution http://ternarylabs.com/2011/03/27/secure-cross-domain-iframe-communication/ currently being used by the Google JavaScript API

edit5: dropbox domain name changed to 'dl.dropboxusercontent.com'

Solution 2:

To be able to set the location.hash you must first get the location. The same origin policy forbids you from getting the location.

Solution 3:

Sounds like this is a bug in Firefox, filed in Bugzilla, according to EricLaw.

Solution 4:

Are all the frames containing locations with the same origin? (eg. same protocol, same domain, same port). If they're not it's a potential security vulnerability if one frame can modify the other -- google the same origin policy. But without more details it's difficult to provide a better answer.

Solution 5:

I can't answer the why bit for the hash, but have you seen John Resig's work with postMessage? You're having trouble with FF3, FF3 happens to be one of the browsers that support postMessage, bingo :-)

Failing that, there's the xssinterface library. Seems to be stable, but I haven't personally tried it.

Post a Comment for "Why Can't An Iframe Set Its Parent's Location.hash?"