Best way to detect when a user leaves a web page?

前端 未结 8 2379
太阳男子
太阳男子 2020-11-22 01:57

What is the best way to detect if a user leaves a web page?

The onunload JavaScript event doesn\'t work every time (the HTTP request takes longer than t

8条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:16

    Mozilla Developer Network has a nice description and example of onbeforeunload.

    If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):

    window.addEventListener('beforeunload', function(e) {
      var myPageIsDirty = ...; //you implement this logic...
      if(myPageIsDirty) {
        //following two lines will cause the browser to ask the user if they
        //want to leave. The text of this dialog is controlled by the browser.
        e.preventDefault(); //per the standard
        e.returnValue = ''; //required for Chrome
      }
      //else: user is allowed to leave without a warning dialog
    });
    

提交回复
热议问题