How to call a function before leaving page with Javascript

前端 未结 8 592
遇见更好的自我
遇见更好的自我 2020-12-05 13:50

I would like to execute a function before leaving page without showing a confirmation popup with Javascript only. I\'ve tried with the code below but it did

8条回答
  •  渐次进展
    2020-12-05 13:58

    Please try below simple code -

    Jquery Code Example -

    $(window).bind('beforeunload', function(){
      Func_ToInsert_Record();
      Alert('Thanks And Bye!');
    });
    

    Javascript Code Example -

    // Anonymous function 
    window.onbeforeunload = function(event) {
      var message = '';
      if (window.event) {
        console.log(window.event);
        console.log(event.currentTarget.performance);
        console.log(event.currentTarget.performance.navigation);
        console.log(event.currentTarget.performance.navigation.type);
    
      } 
    
      event = event || window.event;
      event.preventDefault = true;
      event.cancelBubble = true;
      event.returnValue = message;
    }
    

提交回复
热议问题