How do i open a Bootstrap Modal when the user is trying to refresh or leave the page? The Modal should say something like: '“Are you sure you want to navigate away from this page? ”
I've following Code:
window.onbeforeunload = function() {
$('#myModal').modal("show");
return "Data will be lost if you leave the page, are you sure?";
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to navigate away from this page?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">No I want to stay</button>
<button type="button" class="btn btn-primary">Yes, I'm sure</button>
</div>
</div>
</div>
</div>
But with this codesnippet the modal opens but the page refreshes anyways.