gpt4 book ai didi

javascript - 如何使用 JavaScript 在 IE 中将 iframe 父(顶部)位置更改为相对于 iframe 的 url?

转载 作者:搜寻专家 更新时间:2023-11-01 04:10:04 25 4
gpt4 key购买 nike

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 相关的 URL 的浏览器中工作?


注意:

这可以在 HTML 中完成,例如:<a href="/test" target="top">Test</a>如评论中所述。参见 this question .

但是,我需要(编辑)一个基于 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>

我找到了从 this SO answer 获取基本 url (window.location.origin) 的代码

关于javascript - 如何使用 JavaScript 在 IE 中将 iframe 父(顶部)位置更改为相对于 iframe 的 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com