【问题标题】:Internet Explorer - Check if permission deniedInternet Explorer - 检查权限是否被拒绝
【发布时间】:2012-10-25 17:24:07
【问题描述】:

我在 Internet Explorer 8 中有以下代码:

if (window.opener != null && window.opener.foo != null)  window.opener.foo = bar;

有时会设置window.opener。但是,如果用户打开一个弹出窗口然后离开,则应避免尝试在其上设置属性。

在 Firefox 和 Chrome 中,这是可行的,因为一旦用户退出或刷新该窗口,window.opener 就会变为 null。然而,在 IE 中,window.opener 不为 null,window.opener.foo 给出“Permission Denied”而不是 null。因此,window.opener.foo != null 的计算结果为 true。

如何解决这个问题,Internet Explorer 中的“Permission Denied”是什么值?

【问题讨论】:

    标签: javascript internet-explorer


    【解决方案1】:

    这是我在 IE8 中使用的检查:

    if (window.opener && !window.opener.closed) {
        // do what you will with window.opener
    }
    

    编辑:如果你想显示一个友好的错误,你可以试试这样的:

    try {
        if (window.opener && window.opener.foo != null) {
            window.opener.foo = bar;
        }
    } catch (e) {
        if (e.description.toLowerCase().indexOf('permission denied') !== -1) {
            // handle it nicely
        } else {
            // some other problem, let it blow up
            throw e;
        }
    }
    

    这使您可以专门处理“拒绝访问”错误,而不会隐藏任何其他潜在错误。

    【讨论】:

    • @AndrewLatham 如果用户刷新页面,那么窗口应该关闭。你想完成什么?
    • 在 IE8 中,对我来说,刷新导致它仍在思考 window.opener。关闭是错误的。我正在尝试在弹出窗口中访问父页面的属性,同时在权限被拒绝时显示错误消息(如果父页面被刷新或退出,则会出现这种情况)。在 Firefox/Chrome 中,我可以通过检查 window.opener 是否为空来检测这一点。
    • 基本上,我希望能够在不执行 try-catch 的情况下找出权限是否被拒绝,这可能是任何事情。
    • @AndrewLatham 看到我的编辑,它并不漂亮,但它可能是唯一的方法。
    • 很公平,我得出了同样的结论。
    【解决方案2】:

    如果你在 IE 中无法访问 window.opener 的属性,那么将它传递给 Object.keys() 将返回一个长度为 0 的字符串。

    示例用法:

    if (window.opener && Object.keys(window.opener).length) {
      // do what you will with window.opener
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 2011-08-09
      • 1970-01-01
      • 2020-02-05
      • 2014-12-12
      • 1970-01-01
      • 2014-09-27
      • 2014-10-19
      • 1970-01-01
      相关资源
      最近更新 更多