开发者

Allow iframe links to target parent frames cross domain

I have 2 domains. One page on domain1 uses an iframe to load content from domain2. How do I allow li开发者_JAVA技巧nks from domain2 (inside the iframe) open in the full parent frame on domain1?

I've been looking at IEs application attribute and w3c's new sandbox attribute but I'm unsure how to implement these and if they're compatible cross browser. has anyone any other tricks to get around this?

Is there something I can do with a javascript pixel maybe?


You need to use postMessage() for sending data across domains.

1. Code up the links on domain2.com (the links inside the iframe):

<a href="javascript:;" onclick="top.postMessage('newpage.html','http://domain2.com')"></a>

2. Catch the message in the head of the page on domain1.com (the parent page) and navigate:

window.addEventListener( "message", function(e){
    window.location.href = e.data  //navigates to newpage.html
}, false)

Similar issue here if you need more detais. For < IE8 and other old browsers, there are some hacky workarounds on this page which look quite comprehensive.


You could use Javascript to override the A tags and point them to the window.parent.

http://jfcoder.com/test/iframe_open.html

window.onload = function(){
    var a = document.getElementsByTagName('a');
    for (var i = 0; i < a.length; i++) {
        a[i]['_href'] = a[i].href;
        a[i].href = '#';
        a[i].onclick = function(){
            window.parent.location = this._href;
            return false;
        }
    }
}

Obviously, this is not the code you'd necessarily want to use in your final code, just a proof of concept. But this works in IE9, FF4 and Chrome (current) without any issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜