R K R K - 1 month ago 24
Javascript Question

Alert not showing before unloading

<!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.

Jim Jim
Answer

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>