<script language="javascript">
g_blnCheckUnload = true;
function RunOnBeforeUnload() {
if (g_blnCheckUnload) {window.event.returnValue = 'You will lose any unsaved content';
}
}
</script>
<body onbeforeunload="RunOnBeforeUnload()">
</body>
firefox和IE都支持onbeforeunload事件
用法:
- 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
本文详细介绍了onbeforeunload事件的使用方法及应用场景。此事件在用户尝试离开页面时触发,可用来提醒用户保存未完成的工作。文章列举了多种触发onbeforeunload事件的情况,并提供了具体的JavaScript代码示例。

被折叠的 条评论
为什么被折叠?



