javascript before leaving the page

javascript before leaving the page  using -'javascript,jquery'

I want to make a confirmation before user leaving the page.If he says ok then it would redirect to new page or cancel to leave.I tried to make it with onunload

<script type="text/javascript">
function con() {
    var answer = confirm("do you want to check our other products")
    if (answer){

        window.location = "";

<body onunload="con();">
<h1 style="text-align:center">main page</h1>

but it confirm after page already closed?How to do it properly.It would be even better if someone shows how to do it with jquery?Any help would be greatly appreciated.Thanks in advance

asked Sep 22, 2015 by deepak07.s
0 votes

5 Answers

0 votes

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

If you want to show a prompt before the user leaves the page, use onbeforeunload:

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

Or with jQuery:

$(window).bind('beforeunload', function(){
  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() {

Or with jQuery:

answered Sep 22, 2015 by deepak
0 votes

This code when you also detect form state changed or not.

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

answered Sep 22, 2015 by amit.gupta
0 votes

In order to have a popop with Chrome 14+, you need to do the following :

jQuery(window).bind('beforeunload', function(){
    return 'my text';

The user will be asked if he want to stay or leave.

answered Sep 22, 2015 by deepak07.s
0 votes

This will alert on leaving current page

answered Sep 22, 2015 by mtabakade
0 votes

This post is rather old, but for the records (or someone finding this page via Google): You might as well consider this plugin on github: It fires an event when someone is entering the address bar. I would not rely on it. but it might be an unobtrusive way to ask for feedback.

answered Sep 22, 2015 by mca.agarwal