How can i restrict page loading on reload option (browser)?

两盒软妹~` 提交于 2020-01-03 03:51:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!