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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14590865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:02:28  来源:igfitidea点击:

How to change iframe parent (top) location to url relative to iframe in IE with JavaScript?

javascriptiframecross-browserrelative-path

提问by Zach Lysobey

exampleA.com

exampleA.com

<iframe src="http://exampleB.com/">

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).

在 Chrome(我假设大多数浏览器)中,单击 iframe 内的“测试”按钮会将父页面更改为exampleB.com/test,但在 IE 中它会设置相对于父 URL ( exampleA.com/test) 的位置。

How can I make the test button work in all browsers with a URL relative to the iframe?

如何使用相对于 iframe 的 URL 使测试按钮在所有浏览器中工作?



NOTE:

注意

This can be done in HTML like: <a href="/test" target="top">Test</a>as mentioned in the comments. See this question.

这可以在 HTML 中完成,如: <a href="/test" target="top">Test</a>如评论中所述。看到这个问题

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.

但是,我需要(ed)一个基于 JavaScript 的解决方案,用于响应事件而不是鼠标单击来更改父位置。

采纳答案by Zach Lysobey

Looks like I've answered my own question...

看起来我已经回答了我自己的问题......

exampleB.com

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

我找到了从这个 SO 答案中获取基本 url (window.location.origin) 的代码