jQuery OnBeforeUnLoad Not Working Properly
Usually when using Javascript onbeforeunload to detect page reload or page refresh events, if the refresh or reload is detected, a popup appears displaying a message and the options to either cancel or leave the page.
The problems I'm having is number one, my custom message is not displayed but instead a default message is displayed in Chrome. And two, I would like to call a method when a user clicks the Leave Page option.
I've read that this can be achieved using the unload function but it is not working inside of jQuery document ready. Below is what I have tried:
- function MyMethod(){
- // do something
- }
- $(document).ready(function(){
- $(window).on("unload", function () {
- MyMethod();
- });
- $(window).on('beforeunload', function () {
- return "Refreshing or leaving this page will cause you to lose data!"
- });
- });