You can try the following:
$(document).on('mousedown', 'a[href]', offBeforeUnload) .on('mouseleave', 'a[href]', function () { $(window).on('beforeunload', windowBeforeUnload); }); function offBeforeUnload(event) { $(window).off('beforeunload'); } function windowBeforeUnload() { if (!confirm("some message here")) { return "Are you sure?"; } else{ return false; } } $(window).on('beforeunload', windowBeforeUnload);
Demo
source share