【问题标题】:IE8+, window.open(url/#/frag,'_parent') vs. parent.location.href=url/#/frag in iframeIE8+, window.open(url/#/frag,'_parent') 与 iframe 中的 parent.location.href=url/#/frag
【发布时间】:2014-07-29 00:33:12
【问题描述】:

我有一个加载 iframe 的网站。父窗口中的代码注册了一个 onbeforeunload 监听器。

当前 iframe 包含一个带有触发点击处理程序的按钮:

window.open(/#/frag,'_parent')

在我测试过的所有浏览器中(除了 IE8/IE9),它具有加载父片段而不触发 onbeforeunload 事件的预期行为。 但是,如果我将 iframe 的点击处理程序更改为触发:

parent.location.href='/#/frag'

它在 IE 8/9 中也可以正常工作。

谁能解释这种行为?

下面我举了一个简单的例子:

index.html

<!DOCTYPE html>
<html>
    <head>
        <script>
            function registerUnloadListener(){
                window.onbeforeunload = function (e) {
                    return "onbeforeunload";
                };
            }
        </script>
    </head>

    <body onload="registerUnloadListener()">
        <iframe width="100%" src="iframe.html"></iframe><br/>
    </body>
</html>

iframe.html

<!DOCTYPE html>
<html>
    <head>
        <script>
            function setParentLocation(frag){
                parent.location.href = frag;
            }
            function openWindowInParent(frag){
                window.open(frag,'_parent');
            }
        </script>
    </head>
    <body>
        onbeforeunload triggered (as expected) -->
        <a href="javascript:void(0);" onclick="setParentLocation('/')">
            parent.location.href = '/'
        </a><br/>

        onbeforeunload NOT triggered (as expected) -->
        <a href="javascript:void(0);" onclick="setParentLocation('/#/frag')">
            parent.location.href = '/#/frag'
        </a><br/>

        onbeforeunload triggered for IE8/IE9 only (unexpected) -->
        <a href="javascript:void(0);" onclick="openWindowInParent('/#/frag')">
            window.open("/#/frag",'_parent')
        </a>
    </body>
</html>

提前感谢您的任何反馈。

【问题讨论】:

  • 您是否在问“为什么 Internet Explorer 会做错事或愚蠢的事?”的形式? Internet Explorer 是一种自然的力量,解释并没有多大帮助。
  • @Pointy 我想我想确认 IE 做错了,其他浏览器做对了。

标签: javascript iframe window.open fragment-identifier window.parent


【解决方案1】:

尝试将return false; 添加到您的主播的onclick 事件中。在 IE 中使用 href="javascript:void(0); 触发 onbeforeunload 是一个已知问题,但在点击处理程序中添加 return false; 可以解决此问题。

<a href="javascript:void(0);" onclick="openWindowInParent('/#/frag'); return false;">
    window.open("/#/frag",'_parent')
</a>

【讨论】:

  • @pe p 谢谢,这是有用的信息,但在我的情况下它并不能阻止 onbeforeunload
  • 我想知道差异是否是由于在框架内有链接。祝你好运,我想知道你是否能够解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
相关资源
最近更新 更多