The cause of the incident is due to the customer reflected in the work, often there are users in the process of browsing the web order the merchandise, but because the user suddenly open the window too much, or when tapping the keyboard, incorrectly pressed to the F5 key, causing the page to refresh or abnormal shutdown, and at this time on the page to do all the operation The information is lost, if we can provide a prompt when customer information is not processed, then how good, the following code can be done regardless of the user is clicked off, or in the taskbar close, click Back, refresh, press F5 key, can detect the user is about to leave the message.
<script type="text/javascript" language="javascript">
function bindunbeforunload()
{
window.onbeforeunload=perforresult;
}
function unbindunbeforunload()
{
window.onbeforeunload=null;
}
function perforresult()
{
return"当前操作未保存,如果你此时离开,所做操作信息将全部丢失,是否离 开?";
}
</script>
Only need to register the Bindunbeforunload () method on the page to be detected, you can be in the body of the onload or Document.ready register this method, where we use the Window.onbeforeunload, that is, before the page will be uninstalled before the pop-up prompt box, OK, now to test, test code:
<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();">
<input type="button" value="绑定事件" id="btnBind" onclick="return biindunbeforunload();"/>
<input type="button" value="删除绑定事件" id="btnUnBind" onclick="unbiindunbeforunload();"/>
</body>