'How to show alert on browser back button click event using jquery

I want to show alert while clicking on the back button in the browser. it only works before clicking on the back button, when you click to somewhere else on the page, otherwise, it will go to the previous page without alert message.

I have added my code here. I want to go back when the page loads.

    $(document).ready(function() {
        if (window.history && window.history.pushState) {
        //window.history.pushState('', null, './');
        window.history.pushState(null, "", window.location.href);
        $(window).on('popstate', function() {
            alert('Warning! Your data will lose.');
            document.location.href = 'www.redirecturl.com';

        });
     }
    });
<html>
<head>
    <title>Disable Browser Back Button Using JavaScript</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js">
        </script>
</head>
<body>
    <a href="Page2.html">Click Here...</a>
</body>
</html>

I am using JQuery here



Solution 1:[1]

You can achieve this using onbeforeunload event

using jquery

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

function myFunction(){
     // Write your business logic here
     alert('Bye');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>

Using Javascript

window.onbeforeunload = s => "";
<body>

<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>

</body>

Solution 2:[2]

Put It in your JS file and it will work .. when your press the browser back button it will alert you to leave or cancel.

 $(window).bind('beforeunload', function(){
            return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
        });

Solution 3:[3]

history.pushState(null, document.title, location.href);
  window.addEventListener("popstate", function (event) {
    $.confirm({
      boxWidth: "30%",
      title: "Alert",
      model: true,
      content: "The Changes made will be cleared",
      buttons: {
        Continue: function () {
          history.back();
        },
        Cancel: function () {
          history.pushState(null, document.title, location.href);
        },
      },
    });

  });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Syed Taha
Solution 3 Umesh Bhuibhar