IE8 +,window.open(url /#/ frag,'_ parent')与iframe中的parent.location.href = url /#/ frag

时间:2014-07-26 15:39:24

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

我有一个加载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>

提前感谢您的任何反馈。

1 个答案:

答案 0 :(得分: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>