IE8+, window.open(url/#/frag,'_parent') vs. parent.l

IE8+, window.open(url/#/frag,'_parent') vs. parent.location.href=url/#/frag in iframe

本文关键字:parent vs frag open window url IE8+      更新时间:2023-09-26

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

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

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

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

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

它在ie8/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>

提前感谢您的反馈

尝试将return false;添加到锚的onclick事件中。这是一个已知的问题,锚与href="javascript:void(0);触发onbeforeunload在IE中,但添加return false;到点击处理程序修复。

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