Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change iframe parent (top) location to url relative to iframe in IE with JavaScript?

exampleA.com

<iframe src="http://exampleB.com/">

exampleB.com

<button onclick="top.location='/test'">Test</button>

In Chrome (and I assume most browsers), clicking on the "Test" button inside the iframe changes the parent page to exampleB.com/test, but in IE it sets the location relative to the parent URL (exampleA.com/test).

How can I make the test button work in all browsers with a URL relative to the iframe?


NOTE:

This can be done in HTML like: <a href="/test" target="top">Test</a> as mentioned in the comments. See this question.

However, I need(ed) a JavaScript-based solution for the parent location to be changed in reaction to an event, rather than a mouse click.

like image 702
Zach Lysobey Avatar asked Jan 29 '13 19:01

Zach Lysobey


1 Answers

Looks like I've answered my own question...

exampleB.com

<button onclick="topLocation('/test')">Test</button>

<script>
var topLocation = function(url) {
    // make sure its a relative url
    if (url[0] === '/' && url[1] !== '/'){
        // x-broswer window.location.origin 
        if (!window.location.origin) window.location.origin = window.location.protocol+"//"+window.location.host;
        window.top.location = window.location.origin + url;
    } else {
        window.top.location = url;
    }
}
</script>

I found the code to get the base url (window.location.origin) from this SO answer

like image 83
Zach Lysobey Avatar answered Sep 23 '22 17:09

Zach Lysobey