是否可以以编程方式触发onb​​eforeunload事件?

我目前正在使用jquery-form-observe插件,该插件使用onbeforeunload来提示用户“未保存”的更改。

但是我有一个场景,我需要在按钮点击时触发它:按钮点击最终导致页面更改,但我想在用户启动按钮点击开始的过程之前提示用户…

那么有没有办法通过jQuery或其他方式触发onb​​eforeunload?

我不知道是否有直接的方法可以做到这一点,但您可以自己模拟浏览器的确认框。 这是我根据MSDN的规范制作的一个简单的function:

function triggerBeforeUnload() { var event = {}; handler(event); if (typeof event.returnValue == 'undefined' || confirm('Are you sure you want to navigate away from this page?\n\n' + event.returnValue + '\n\nPress OK to continue, or Cancel to stay on the current page.')) { // Continue with page unload } else { // Cancel page unload } } 

编辑:jquery.formobserver.js ,在function beforeunload(e) { ... }的定义之后,添加以下行:

 handler = beforeunload; 

请注意原始代码中的更改: window.onbeforeunload已被handler替换。

您可以使用.trigger()方法执行此操作:

 $('button').click(function(){ $(window).trigger('beforeunload'); });