6

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.

Community
  • 1
  • 1
Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149
  • Why not use a link? `Test` should resolve the `href` to the current frame, then navigate the parent to it. If that doesn't work `Test` should. – Niet the Dark Absol Jan 29 '13 at 19:42
  • my example is much simpler than the actual code in production. There is no button. The parent page is changed automatically in response to an ajax call from within the iframe which generates a url fragment dynamically – Zach Lysobey Jan 29 '13 at 19:46

1 Answers1

5

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

Community
  • 1
  • 1
Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149