How to redirect a page to another page when refresh at second attempt
Asked Answered
B

5

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

I tried this code, but it is not working.

Bosom answered 24/12, 2011 at 5:24 Comment(2)
what are you trying to do? keep users from leaving your site? But only the second time they try and leave?Benares
@Bosom if my code solves your probem vote for answer and mark as accepted answer so that other peoples can use this code.Jackboot
Q
16

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 
}
Quidnunc answered 26/10, 2015 at 11:17 Comment(1)
It works perfectly! @Lokesh, Could you please explain how this works? How does it work with setTimeOut function?Ers
A
3

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";
}
Abelmosk answered 18/11, 2019 at 6:58 Comment(0)
J
2

below code will work for you

function confirmExit()
{
 alert("exiting");
 window.location.href='index.html';
 return true;
}
window.onbeforeunload = confirmExit;
Jackboot answered 24/12, 2011 at 9:29 Comment(0)
W
2

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!

Wraf answered 5/6, 2020 at 6:48 Comment(0)
R
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';
});
Rising answered 11/7, 2016 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.