Javascript 当iframe跨域时进行检测,然后跳出它

Javascript 当iframe跨域时进行检测,然后跳出它,javascript,security,iframe,cross-domain,Javascript,Security,Iframe,Cross Domain,我有一个包含大部分内容的大iframe页面。用户通过在iframe中单击与网站交互。我试图构建的功能是:当用户离开我的站点时,我会帮他们一个忙,然后跳出iframe iframe有一个onload事件,无论是否跨域加载新页面,该事件都会在每次加载时触发 <iframe id="testframe" src="http://mysite.com" onload="testframe_loaded()"></iframe> 当iframe跨域时。我也不确定是否有可能 如果有

我有一个包含大部分内容的大iframe页面。用户通过在iframe中单击与网站交互。我试图构建的功能是:当用户离开我的站点时,我会帮他们一个忙,然后跳出iframe

iframe有一个onload事件,无论是否跨域加载新页面,该事件都会在每次加载时触发

<iframe id="testframe" src="http://mysite.com" onload="testframe_loaded()"></iframe>
当iframe跨域时。我也不确定是否有可能

如果有人对如何做到这一点有想法,或者肯定这件事做不到,我会很感激你的建议


谢谢

你可以做一个,因为如果你得到一个安全错误(你可以捕捉到),这意味着它们是跨域的:),那么你可以调整iframe的大小,使之成为整个页面。但我认为你是对的,如果没有其他领域的明确合作,你实际上不可能脱身

编辑:你是对的,你不需要投票。以下是基本代码:

<html>
<head>
<title>Cross-domain frame test</title>
<!-- http://stackoverflow.com/questions/2365822/detect-when-iframe-is-cross-domain-then-bust-out-of-it/2365853#2365853 -->
<script type="text/javascript">
function checkForCross()
{
  var iframe = document.getElementById("myFrame");
  try
  {
    var loc = iframe.contentDocument.location.href;
  } catch(e)
  {
    iframe.setAttribute("style", "border: 0; margin: 0; padding: 0; height: 100%; width: 100%;");
  }
}
</script>
</head>
<body>
<iframe name="myFrame" id="myFrame" src="child.html" style="height: 50%; width: 50%;" onload="checkForCross()"></iframe>
</body>
</html>

跨域帧测试
函数checkForCross()
{
var iframe=document.getElementById(“myFrame”);
尝试
{
var loc=iframe.contentDocument.location.href;
}捕获(e)
{
setAttribute(“样式”,“边框:0;边距:0;填充:0;高度:100%;宽度:100%);
}
}

将外部链接上的“target”属性设置为“\u top”。

这至少适用于chrome(在其他浏览器上不适用)


它仍然会抛出
“不安全的javascript尝试”
警告,但这不会停止代码执行。相反,该变量返回为未定义。

我将测试try/catch方法。。我总是忘记JavaScript支持:)轮询是不必要的,因为我可以在每次触发iframe的onload事件时测试它。这肯定是有效的,并且证明了轮询是可能的。不幸的是,B似乎仍然不可能——扩展iframe是可行的,但它仍然不可靠,因为浏览器位置栏中的url与显示的站点不匹配。我将尝试使用一些涉及修改其他答案建议的链接的解决方案,例如,在检查href属性是否为跨域的每个链接上附加一个单击处理程序。Emmett,单击处理程序工作,但仅适用于/your/链接,而不适用于iframe内的链接。据我所知,try/catch块不能阻止在Chrome或Safari的错误控制台中出现错误。有人知道如何在这些浏览器中进行搜索吗?这个错误是无法捕获的(至少在chrome上是如此)。继续执行,但对任何跨域变量的访问返回为未定义。请参阅下面我的答案,以获取代码示例。在不跨域时,可以通过遍历BOM来执行此操作。
<html>
<head>
<title>Cross-domain frame test</title>
<!-- http://stackoverflow.com/questions/2365822/detect-when-iframe-is-cross-domain-then-bust-out-of-it/2365853#2365853 -->
<script type="text/javascript">
function checkForCross()
{
  var iframe = document.getElementById("myFrame");
  try
  {
    var loc = iframe.contentDocument.location.href;
  } catch(e)
  {
    iframe.setAttribute("style", "border: 0; margin: 0; padding: 0; height: 100%; width: 100%;");
  }
}
</script>
</head>
<body>
<iframe name="myFrame" id="myFrame" src="child.html" style="height: 50%; width: 50%;" onload="checkForCross()"></iframe>
</body>
</html>
   if(parent.location.host != undefined){ 
       alert("hello world!");
    }else{
       throw "cannot access parent!";
    }