Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop unloading the page?

I have a page where user needs to enter some data and click save to validate the changes, but my problem is if the user is trying to close the browser window or click on a different link to navigate to a different page..I need to delete all the entries the user has saved so far.. I am doing it the following way

window.onbeforeunload = function() 
{
 if(confirm('Are you sure you want to navigate'))
  {
    //Invoke `enter code here`server side method
  }
 else
 {
   // return false;
 }
}

Everything works fine if he click on Yes, the problem comes when he click on "No"..Even if he click on No..the page unload method is getting called and it is redirected to a different page..but I want it to stay in the same page in same state...can you please help me in achieving this.

Thanks and appreciate your response....

like image 876
user788312 Avatar asked Jan 17 '23 03:01

user788312


2 Answers

You cannot stop the user from leaving the page. What you can do is alert a message to them, asking if they want to leave or not.

The window.onbeforeunload event should return a string (and only a string). This string will be printed on the alert box made by the browser.

You cannot use your own alert box, or block the user from leaving (or redirect them).

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

Or with jQuery

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

When a user leaves the page, you can use the onunload event to make an AJAX call (you may need to use async: false here).

Example:

$(window).unload(function(){
    $.ajax({
        url: '/path/to/page/',
        async: false, // this may be needed to make sure the browser doesn't
                      // unload before this is done
        success: function(){
          // Do something
        }
    });
});

NOTE: Instead of doing this, why don't you just save everything when the user is completed? Instead of saving it and then removing it if the user doesn't finish?

like image 199
Rocket Hazmat Avatar answered Jan 20 '23 14:01

Rocket Hazmat


First of all: you can't! It's impossible. onbeforeunload only accepts a string as return value and will then close if the user wants that.

But then think about what happens if the computer is being without energy and shuts down? Or the browser will closed by the Task Manager? Or even more "realistic": The internet connection get lost! => Then you got invalid data states too!

You are trying to solve a false problem! Your problem isn't this function, your problem is the state of your formular!

Why do you need some kind of function? Do you saving the data before he clicks on save? Then don't! Or make sure to have another query which detects unfinished data in your database and delete it after a timeout!

like image 24
Neysor Avatar answered Jan 20 '23 15:01

Neysor