Allow iframe links to target parent frames cross d

2019-08-01 16:35发布

问题:

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 compatible cross browser. has anyone any other tricks to get around this?

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

回答1:

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.



回答2:

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.