简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM