How to change iframe parent (top) location on 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 the Test button inside the iframe changes the parent page to exampleB.com/test, but in IE it sets the location relative to the source URL ( exampleA.com/test).

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


Note

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

However, I need a (ed) JavaScript-based solution for the parent location that needs to be changed in response to the event, not a mouse click.

+5
1

, ...

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>

url (window.location.origin) SO-

+5

All Articles