用户尝试离开页面时创建确认弹出窗口

时间:2019-04-16 19:45:58

标签: javascript

基本上,我在公司内部网站上使用此代码,我们要确保如果用户填写表格而他们不小心单击了指向其他页面的链接,那么他们不会丢失他们的信息的形式。我已经尝试过在JavaScript中使用window.onbeforeunload并没有运气,所以我转到了jquery:

我尝试使用window.onbeforeunload,似乎没有做任何事情。 jQuery中的绑定前卸载相同的东西:

    jQuery($(window).bind('beforeunload', function(){
        confirm('Are you sure you want to leave? Any information in "Notify" will be lost.');
    }));

1 个答案:

答案 0 :(得分:2)

您没有正确使用beforeunload

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
<a href="https://example.com">Leave</a>

相关问题