问题
i have a jsp page and i want to prevent it from reloading, if a user click on refresh then a dialogue box must be shown and ask for Confirm/Stay here. if user click on confirm the form must be submitted otherwise the page shouldn't refresh.
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave?';
if (evt) {
document.forms["myForm"].submit();
}
else {
}
return message;
}
</script>
<form action="SubmitExam.jsp" method="post" id="myForm"> My Code</form>
回答1:
This one should work. See: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
回答2:
what you want to do, is not possible using event, there's no way captures the return of this event, what you can do is try to make the User answer before pressing the button to reload or close tab
function onMouseLeave(e){
var pageX = e.pageX || e.clientX;
var pageY = e.pageY || e.clientY;
if (pageX < 0 || pageY < 0 || pageY < top) {
if(confirm('exit intension ?')){
alert('yes');
}else{
alert('no');
}
}
}
var body = document.body;
body.addEventListener('mouseleave',onMouseLeave);
来源:https://stackoverflow.com/questions/34767942/how-can-i-restrict-page-loading-on-reload-option-browser