6
<script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
   alert("");window.location="index.html";
  }
</script>

I tried this code, but it is not working.

halfer
  • 19,824
  • 17
  • 99
  • 186
sss
  • 61
  • 1
  • 1
  • 2

5 Answers5

15

In bbb.jsp:

window.onbeforeunload = function() { 
    window.setTimeout(function () { 
        window.location = 'AAA.jsp';
    }, 0); 
    window.onbeforeunload = null; // necessary to prevent infinite loop, that kills your browser 
}
arghtype
  • 4,376
  • 11
  • 45
  • 60
Biyu
  • 513
  • 1
  • 5
  • 30
  • It works perfectly! @Lokesh, Could you please explain how this works? How does it work with setTimeOut function? – Gsm Sep 12 '17 at 22:48
2

Windows onload loads after all the content is loaded, little bit slow other workaround is to use document.onload(Browser compatibility issue)

window.onload = function () {
  window.location = "/allotment";
}
sachin babu
  • 152
  • 1
  • 8
2

below code will work for you

function confirmExit()
{
 alert("exiting");
 window.location.href='index.html';
 return true;
}
window.onbeforeunload = confirmExit;
Robin Michael Poothurai
  • 5,444
  • 7
  • 23
  • 36
1

In bbb.jsp file

<script>
    submitFormOkay = false;
    $(document.body).on("click", "a", function() {
        submitFormOkay = true;
    });
    window.onbeforeunload = function(event) {
        event.preventDefault(); 
        if (!submitFormOkay) {
            window.setTimeout(function () { 
                window.location = "index.html";
            }, 0); 
            window.onbeforeunload = null;
        }
    }
</script>

I hope this will help. Cheers!

Chandni Soni
  • 377
  • 4
  • 16
0

This has worked for me. Not the second attempt part, but changing URL after showing the popup. If you hit cancel, the function is not ran. If you click "Reload", the function is called and you will be redirected.

$(window).on('beforeunload', function() {
  $(window).on('unload', function() {
    window.location.href = 'index.html';
  });

  return 'Not an empty string';
});
JLev
  • 43
  • 5