注:三大主流瀏覽器中firefox和IE都支持onbeforeunload事件,opera尚未支持。
用法:
- object.onbeforeunload = handler
- <element onbeforeunload = “handler” … ></element>
描述:
事件觸發的時候彈出一個有確定和取消的對話框,確定則離開頁面,取消則繼續待在本頁。
handler可以設一個返回值作爲該對話框的顯示文本。
觸發於:
- 關閉瀏覽器窗口
- 通過地址欄或收藏夾前往其他頁面的時候
- 點擊返回,前進,刷新,主頁其中一個的時候
- 點擊 一個前往其他頁面的url連接的時候
- 調用以下任意一個事件的時候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
- 當用window open打開一個頁面,並把本頁的window的名字傳給要打開的頁面的時候。
- 重新賦予location.href的值的時候。
- 通過input type=”submit”按鈕提交一個具有指定action的表單的時候。
可以用在以下元素:
BODY, FRAMESET, window
平臺支持:
IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+
<script language="javascript">
var g_blnCheckUnload = true;
function RunOnBeforeUnload() {
if (g_blnCheckUnload) {window.event.returnValue = 'You will lose any unsaved content';
}
}
function turnToOtherPage(){
g_blnCheckUnload = false;
//在此處添加你自己需要處理的方法,或頁面跳轉的連接
g_blnCheckUnload = true;
}
</script>
<body οnbefοreunlοad="RunOnBeforeUnload()">
<input type="button" name="TrampEagle" value="TurnToPage" οnclick="turnToOtherPage()">
</body>
<script language="javascript">
g_blnCheckUnload = true;
function RunOnBeforeUnload() {
if (g_blnCheckUnload) {window.event.returnValue = 'You will lose any unsaved content';
}
}
</script>
<body οnbefοreunlοad="RunOnBeforeUnload()">
</body>
這樣每次關閉瀏覽器窗口或涮新頁面時,都要觸發onbeforeunload這個事件,這樣可以對用戶進行提示,避免不必要的遺憾。
<script language=javascript>
function window.onbeforeunload()
{
if(event.clientX>document.body.clientWidth&&event.clientY<0 ¦ ¦event.altKey)
{
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","sessionEnd.asp",false);
xmlhttp.send();
}
}
</script>