0
<!DOCTYPE html>
<html lang="en">
    <head>
         <title>
         </title>
         <meta charset="utf-8" />
         <link rel="stylesheet" type="text/css" href="css/custom.css" />
    </head>
    <body>
          <a href="http://www.google.co.in">Google</a>
    <script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
    <script type="text/javascript" src="js/custom.js" ></script>
    </body>
</html>

below is code in custom.js

$(window).on('beforeunload',function (){
     alert("abc");
});

I want the page to show an alert before going to next page after clicking the link, but it is not showing.

R K
  • 307
  • 7
  • 22
  • *I want the page to show an alert before going to next page after clicking the link* - why? This is really annoying and unfriendly to the user, and that's why browsers have disabled it. If you state the problem you're trying to solve with this alert, maybe we can help you find a better way to achieve your goal. – Ry- Nov 06 '16 at 12:44
  • Well I was just going through a jQuery tutorial, that's why I wanted to do that. – R K Nov 06 '16 at 12:45
  • Checkout [this](http://stackoverflow.com/a/1270421/5549391) answer and the links in the answer – agDev Nov 06 '16 at 13:02
  • You can find my complete answer here: http://stackoverflow.com/questions/38879742/is-it-possible-to-display-a-custom-message-in-the-beforeunload-popup/38880926#38880926 with the explanations and screenshots for each browser. – Dekel Feb 12 '17 at 16:46

2 Answers2

3

the beforeunload works well , but in your case there is no effect due to using the alert which is blocked bu the browser , so you can print in console but you can't use the alert in beforeunload

in the above example i've used console .

$(window).on("beforeunload",function(event){
   console.log("This works , but alert is blocked ");
  
   // alert(""); this wont work and it's blocked by the browser due to window's object missing 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="http://www.google.co.in">Google</a>
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
1

Chrome block alerts in beforeunload because they choose to do so.

You can listen to the click event of the link and throw a confirmation like so:

var link = document.querySelectorAll('a.confirmation')[0];

link.onclick = function () {
    var check = confirm('Are you sure ?');
    if (check === true) {
        return true;
    }
    else {
        return false;
    }
}
<a href="http://www.google.co.in" class="confirmation">Google</a>

or with jQuery

$(".confirmation").on('click', function () {
    var check = confirm('Are you sure ?');
    if (check === true) {
        return true;
    }
    else {
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.google.co.in" class="confirmation">Google</a>
Jim
  • 2,974
  • 2
  • 19
  • 29