Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display modal form before user leaves page

I've used window.onbeforeunload to display a custom message when a user attempts to leave a site.

Example:

window.onbeforeunload = function(){
  if(some_condition){
    return "Are you sure you want to navigate away from this page?\nAll unsaved changes will be lost.";
  }
};


+--------------------------------------------------------+
| Are you sure you want to navigate away from this page? |
| All unsaved changes will be lost.                      |
|                                                        |
|          [ Yes ]  [ Cancel ]                           |
+--------------------------------------------------------+

However, I'd like to enhance this a bit. If possible, I'd like to use a custom modal form instead of the generic popup.

Is there a way to do this?

like image 490
maček Avatar asked Oct 13 '10 20:10

maček


2 Answers

Binding to a html has worked very well for me instead of unload. The reason is well explained in another answer here.

$("html").bind("mouseleave", function () {
    $('#emailSignupModal').modal(); \\or any modal
    $("html").unbind("mouseleave");
});

If you want to show the modal only once in a day or on any other particular condition match then you can use cookies.

like image 194
Mandeep Janjua Avatar answered Nov 12 '22 09:11

Mandeep Janjua


Is there a way to do this?

Nope.

You are stuck with the prompt the browser gives you.

like image 34
epascarello Avatar answered Nov 12 '22 08:11

epascarello