【问题标题】:Is it possible for an iframe to redirect the parent page? [duplicate]iframe 是否可以重定向父页面? [复制]
【发布时间】:2014-09-30 01:20:12
【问题描述】:

iframe 可以重定向它所在的页面吗?

例子:

你去 www.fuu.com

在 fuu.com 上有一个 iframe

在那个 iframe 中是一个重定向到另一个网站的网站。

fuu.com 可以重定向吗?而不是只在 iframe 上转到另一个页面?

【问题讨论】:

  • 重定向是什么意思?但我很确定答案是肯定的。
  • 类似window.top.location.href = "http://example.com";parent.document.location.href = "http://example.com";
  • 哦,您的意思是希望 iframe 重定向“父”页面?在那种情况下,那是不可能的。编辑:其实我觉得我错了,见:*.com/questions/580669/…

标签: javascript php html css


【解决方案1】:

不。 iframe 被视为具有自己的 DOM 的单独文档。 iframe 内的重定向仅被视为该 iframe 内的重定向。

换句话说,主页面不能被 iframe 重定向。

编辑:我错了。考虑以下情况

首页

<html>
<body>
<iframe src="redirect.html"></iframe>
</body>
</html>

redirect.html

<html>
    <head>
        <script>
            window.top.location = "http://www.w3schools.com";
        </script>
    </head>
</html>

确实会将首页重定向到 w3schools.com

为了防止这种类型的事情,您可以使用以下方法将其删除

<html>
<body>
<iframe src="redirect.html" sandbox="allow-scripts"></iframe>
</body>
</html>

在 chrome 中,这会给你以下错误:

Unsafe JavaScript attempt to initiate navigation for frame with URL 'http://127.0.0.1/scg/?search=&submit=Search' from frame with URL 'http://127.0.0.1/scg/iframeRedirect.html'. The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.

allow-scripts 允许 Javascript 仍然在 iframe 中执行,但从允许执行中删除 window.top。 Check this out

【讨论】:

  • window.top.location = "http://www.example.com"; ?
  • 谷歌说不同"redirect from iframe"
  • 我错了。我没有考虑window.top
  • 如果有人使用 Angular / TypeScript,你需要使用 window.top.location.href = "w3schools.com"