How to call a function before leaving page with Javascript

前端 未结 8 543
遇见更好的自我
遇见更好的自我 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:57

    If you want to prompt the user, return a string with the message. If you don't want to prompt the user, don't return anything.

    // Execute code, then prompt the user to stay
    window.onbeforeunload = function () {
      // This will happen before leaving the page
      return 'Are you sure you want to leave?';
    }
    

    Or:

    // Execute code, then leave
    window.onbeforeunload = function () {
      // This will happen before leaving the page
    }
    
    0 讨论(0)
  • 2020-12-05 13:58

    You can always call your function before leaving the page.

    function myfun(){
         // Write your business logic here
         console.log('hello');
    }
    

    onbeforeunload:

    window.onbeforeunload = function(){
      myfun();
      return 'Are you sure you want to leave?';
    };
    

    Or with jQuery:

    $(window).bind('beforeunload', function(){
      myfun();
      return 'Are you sure you want to leave?';
    });
    

    This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

    You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

    window.onunload = function() {
        myfun();
        alert('Bye.');
    }
    

    Or with jQuery:

    $(window).unload(function(){
      myfun();
      alert('Bye.');
    });
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-05 13:58

    I simple put this code and works preety well

    window.onbeforeunload = function(event) {
        $('element').show();
        return;
    };
    
    0 讨论(0)
  • 2020-12-05 13:59

    The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.

    window.addEventListener('onbeforeunload', function(e) {}, false);
    

    You can also just populate the .onunload or .onbeforeunloadproperties of window with a function or a function reference.

    Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.

    0 讨论(0)
  • 2020-12-05 14:07

    Just call your function from within window.onbeforeunload. Note, some browsers restrict what you can do here (eg: no redirects or alerts). See: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload for more info.

    I've also added the appropriate code for readers that do want to show a confirmation dialog.

    function doSomething(){
        //do some stuff here. eg:
        document.getElementById("test").innerHTML="Goodbye!";
    }
    function showADialog(e){
        var confirmationMessage = 'Your message here';
        //some of the older browsers require you to set the return value of the event
        (e || window.event).returnValue = confirmationMessage;     // Gecko and Trident
        return confirmationMessage;                                // Gecko and WebKit
    }
    window.addEventListener("beforeunload", function (e) {
        //To do something (Remember, redirects or alerts are blocked here by most browsers):
        doSomething();    
        //To show a dialog (uncomment to test):
        //return showADialog(e);  
    });
    

    Just hit 'Run' to test: http://jsfiddle.net/2Lv4pa9p/1/

    0 讨论(0)
提交回复
热议问题