How to call a function before leaving page with Javascript

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

提交回复
热议问题