不安全的 JavaScript 尝试启动带有 URL 的框架的导航更改 - 如何尝试捕获它

Unsafe JavaScript attempt to initiate a navigation change for frame with URL - How to try catch it

本文关键字:导航 何尝试 框架 JavaScript 启动 URL 不安全      更新时间:2023-09-26

我的iframe中有这个脚本:

var redirectTo = "http://www.stackoverflow.com";
try {
      parent.location.href = redirectTo;
}catch(e){
      window.open(redirectTo);
    }

浏览器不会捕获主题中的错误。
我希望浏览器在 try 块失败时执行 catch 块。
但是,即使错误发生在 try 块内,浏览器仍然会看到错误。

更新在正常情况下,我的代码工作正常。
当它的 iframe 在 iframe 内时它不起作用,在这些情况下我遇到了安全错误。
你知道Y吗?我如何知道我的 iframe 是否在其他 Iframe 中?

谢谢

您无法在javascript中捕获此类错误,因为它不是javascript错误,而是浏览器安全功能。但是您可以通过检查 url 和当前位置之间的域和端口匹配来防止它。此外,如果父框架与 iframe 的域/端口不同,则无法访问父框架。因此,如果父帧域/端口与子 iframe 不同,除非您已经从其他来源知道它,否则您甚至可能无法获得该位置。你试图做一些你真的不应该做的事情

(更新(检查父节点

var ploc=null
try {
  if (parent && parent.nodeName=="IFRAME")
    ploc=parent.location;//assuming current node is an iframe
}catch(e){
  //it may be an iframe but from another domain
}
if (ploc) ... //ok its an iframe and is from same domain the we can proceed