Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net &引用;“未知异常”;使用“取消页面卸载”时;location.href";_Asp.net_Javascript_Onbeforeunload - Fatal编程技术网

Asp.net &引用;“未知异常”;使用“取消页面卸载”时;location.href";

Asp.net &引用;“未知异常”;使用“取消页面卸载”时;location.href";,asp.net,javascript,onbeforeunload,Asp.net,Javascript,Onbeforeunload,我正在使用以下代码捕获window.onbeforeunload事件: window.onbeforeunload = function (evt) { if(checkIsDirty()) { var message = 'If you continue your changes will not be saved.'; if (typeof evt == 'undefined') {

我正在使用以下代码捕获window.onbeforeunload事件:

window.onbeforeunload = function (evt) 
{

    if(checkIsDirty())
        { 
            var message = 'If you continue your changes will not be saved.'; 
            if (typeof evt == 'undefined') 
            {   
                //IE 
                evt = window.event; 
            } 
            if (evt) 
            { 
                evt.returnValue = message; 
            }
            else
            {
                return message; 
            }
        }

} 
当我在结果确认中单击“取消”时,会出现错误“未知异常”,调试器会突出显示以下内容:

onclick="location.href='/<WhicheverPageYouRequested>.aspx';
onclick=“location.href=”/.aspx';

如果单击“确定”,页面将完全更改。为什么会出现此错误,以及如何修复它?

是的,这是一种已知的IE行为。当您尝试从JavaScript导航时(使用location、location.href、location.replace、document.location、history,甚至是link.click或form.submit等迂回方法),在卸载之前执行
取消将引发异常。测试用例如下所示:

window.onbeforeunload= function() { return '?'; }
location.href= 'http://www.example.com/';
这甚至可能是故意的,让脚本知道导航尝试失败了,只是错误名称完全没有用处。(我得到了“未指定的错误”。)

传统的解决方案就是抓住它:

try {
    location.href= '...';
} catch(e) {}
我一直对此持怀疑态度,因为捕获所有异常通常都是坏消息(但IE不允许您仅捕获此异常…除了检查确切的stringTo,它非常脆弱)

另一种方法是将onbeforeunload工作移动到调用代码中,这样真正的onbeforeunload就不会发生,也不会出现异常:

function navigate(url) {
    if (window.onbeforeunload) {
        if (confirm(window.onbeforeunload()+' Press OK to continue, or Cancel to stay on the current page.')
            window.onbeforeunload= '';
        else
            return;
    }
    location.href= url;
}
然而,如果插入代码的是您正在使用的任何框架,而不是您自己编写的框架,那么这两种解决方案都可能超出您的理解范围

onclick="location.href='/<WhicheverPageYouRequested>.aspx'";
window.onbeforeunload= function() {
    if(checkIsDirty())
        return 'If you continue your changes will not be saved.';
}