从IFrame更改父窗口的URL

Kip*_*Kip 14 html javascript security iframe

我有一种情况,我在两个不同的服务器上有Web应用程序,其中App1在IFrame中包含App2.App2中的任何链接都可以具有target="_parent"属性,允许在顶部窗口中打开这些链接.但是,我找不到任何方法在Javascript中获得相同的行为.我找到了这个页面,声称子框架可以使用父框架调用javascript parent.foo(),但这似乎在IE8或FF3.5中不起作用.我找到了这个问题,解释了这个安全模型的工作原理.但似乎很奇怪,我不能用Javascript做一些简单的<a>标签. 这有什么解决方法吗?我知道window.postMessage,但(据我所知)这只适用于Firefox.


服务器1/test.html中

<html>
<head>
<script type="text/javascript">
function myCallback(foo) {
  alert(foo);
}
</script>
</head>
<body>
<iframe src="http://server2/test2.htm" width="400" height="150"></iframe>
</body></html>
Run Code Online (Sandbox Code Playgroud)

服务器2/test2.html

<html><body>
<script>
function clickit() {
  parent.document.location = "http://www.google.com"; //not allowed
  parent.myCallback("http://www.google.com"); //not allowed
}
</script>
<p>This should be in an iFrame!</p>
<p><a href="http://www.google.com" target="_parent">normal link (works)</a></p>
<p><a href="javascript:clickit()">javascript link</a></p>
</body></html>
Run Code Online (Sandbox Code Playgroud)

Kip*_*Kip 13

好的我做了更多的调查,看起来postMessage适用于所有现代浏览器,甚至是IE(有一点需要注意,IE的做法略有不同).以下是我如何使用它(在IE8,FF3.5,Chrome 3.0,Safari 4 beta,Opera 9.64中的WinXP上测试):

服务器1/test.html中

<html>
<head>
<script type="text/javascript">
if(navigator.appName == "Microsoft Internet Explorer")
  window.attachEvent("onmessage", receiveMessage);
else
  window.addEventListener("message", receiveMessage, false);

function receiveMessage(e) {
  if(e.origin == "http://server2") //important for security
    if(e.data.indexOf('redirect:') == 0)
      document.location = e.data.substr(9);
}
</script>
</head>
<body>
<iframe src="http://server2/test2.htm" width="400" height="150"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

服务器2/test2.htm

<html><body>
<script>
function clickit() {
  parent.postMessage('redirect:http://www.google.com', 'http://server1');
}
</script>
<p>This should be in an iFrame!</p>
<p><a href="http://www.google.com" target="_parent">normal link</a></p>
<p><a href="javascript:clickit()">javascript link</a></p>
</body></html>
Run Code Online (Sandbox Code Playgroud)


Nir*_*hra 5

您可以做的简单事情是:从iframe页面的JavaScript代码执行以下内容

top.location = "https://www.google.co.in/";
Run Code Online (Sandbox Code Playgroud)

这会将窗口URL的位置更改为https://www.google.co.in/

还有一件事-当您不希望任何人可以将您的网站嵌入框架时,只需在文档准备就绪的部分中编写上述代码,该策略也很有用。