[英]Javascript top.location.replace with and without parent iFrame
[英]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>
在Chrome(我假设使用的是大多数浏览器)中,单击iframe中的“测试”按钮会将父页面更改为exampleB.com/test
,但在IE中,它会设置相对于父URL的位置( exampleA.com/test
) 。
如何使用相对于iframe的网址使测试按钮在所有浏览器中都能正常工作?
注意 :
可以在HTML中完成,例如: <a href="/test" target="top">Test</a>
如注释中所述。 看到这个问题 。
但是,我需要基于JavaScript的解决方案来更改父位置,以响应事件,而不是单击鼠标。
看来我已经回答了自己的问题...
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>
我找到了从此SO答案获取基本URL(window.location.origin)的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.