首页 / 脚本样式 / JavaScript / window.onbeforeunload方法在IE下无法正常工作的解决办法
window.onbeforeunload方法在IE下无法正常工作的解决办法2011-08-26 博客园 老米事件的起因是由于在工作中有客户反映,常常会有用户在浏览网页的过程中订 购了商品,但是由于用户一下子打开的窗口过多,又或者在敲打键盘时,错误地 按到了F5键,导致页面刷新或者不正常关闭,而这时在该网页上所做的一切操作 的信息都丢失了,如果我们可以提供一个在客户信息未处理完成时的提示那该多 好啊,下面的代码可以做到不管用户是点击了关闭,或者是在任务栏关闭、点击 后退、刷新、按F5键,都可以检测到用户即将离开的消息。<script type="text/javascript" language="javascript">
function bindunbeforunload()
{
window.onbeforeunload=perforresult;
}
function unbindunbeforunload()
{
window.onbeforeunload=null;
}
function perforresult()
{
return"当前操作未保存,如果你此时离开,所做操作信息将全部丢失,是否离 开?";
}
</script>只需要将bindunbeforunload()方法注册到要检测的页面上即可,你可以在 body的onload或者 document.ready中注册这个方法,在这里我们采用的是 window.onbeforeunload,即是在页面即将卸载之前弹出提示框,好的,现在来测 试一下,测试代码:<html>
<head><title>this is id onbeforunload event test</title>
</head>
<script type="text/javascript" language="javascript">
function bindunbeforunload()
{
window.onbeforeunload=perforresult;
}
function unbindunbeforunload()
{
window.onbeforeunload=null;
}
function perforresult()
{
return"当前操作未保存,如果你此时离开,所做操作信息将全部丢失,是否离 开?";
}
</script>
<body onload="javascript:return bindunbeforunload();">
<h1>test is start</h1>
<input type="button" value="绑定事件" id="btnBind" onclick="return biindunbeforunload();"/>
<input type="button" value="删除绑定事件" id="btnUnBind" onclick="unbiindunbeforunload();"/>
</body>
</html>