最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Allow iframe links to target parent frames cross domain - Stack Overflow

programmeradmin1浏览0评论

I have 2 domains. One page on domain1 uses an iframe to load content from domain2. How do I allow links 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 patible cross browser. has anyone any other tricks to get around this?

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

I have 2 domains. One page on domain1 uses an iframe to load content from domain2. How do I allow links 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 patible cross browser. has anyone any other tricks to get around this?

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

Share Improve this question edited May 30, 2011 at 17:30 cronoklee asked May 30, 2011 at 16:37 cronokleecronoklee 6,7629 gold badges55 silver badges83 bronze badges 2
  • Have you tried target="_parent" on the links in the iframe. – Niklas Commented May 30, 2011 at 16:53
  • Yes, the page loads in a new window and chrome throws an error: Unsafe JavaScript attempt to initiate a navigation change – cronoklee Commented May 30, 2011 at 17:08
Add a ment  | 

2 Answers 2

Reset to default 2

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

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

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

2. Catch the message in the head of the page on domain1. (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 prehensive.

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

http://jfcoder./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)

  1. 暂无评论