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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With