【问题标题】:What is the best way to find out that access to the parent window has restrictions due to the same origin policy?找出由于同源策略而对父窗口的访问受到限制的最佳方法是什么?
【发布时间】:2024-01-24 12:13:01
【问题描述】:

我目前的解决方案:

function isAccessToWindowRestricted(w) {
  try {
    return !w.location.href;
  } catch (e) {
    return true;
  }
}

有更好的想法吗?有没有没有 try-catch 的“合法”方式?

【问题讨论】:

    标签: javascript iframe cross-domain xss same-origin-policy


    【解决方案1】:

    没有什么好办法,因为没有办法在不抛出异常的情况下测试父框架中的值甚至存在

    我只是尝试了一些东西,包括这个:

    var parentURL = window.parent && window.parent.location && window.parent.location.href;
    

    无论如何,由于相同的来源策略,它会抛出异常。但是,您可以检查一下您是否在 iframe 中

    function checkInFrame( arg ){ arg = arg || window; return arg.parent == window; }
    

    但据我所知,您必须使用 try { ... } catch( ... ) { ... } 块(这就是它的用途)。

    【讨论】:

    • 不同浏览器的行为不同。例如,Chrome 不会抛出异常,只会为受限窗口的 location.href 返回 undefined
    • 很高兴知道。不幸的是,除非您只是为 Chrome 用户编写,否则您仍然必须使用 try / catch 块,:(
    最近更新 更多