capture the result of window.onbeforeunload

帅比萌擦擦* 提交于 2019-12-13 22:23:15

问题


I have a scenario, I have to save the changes when user clicks yes on window.onbeforeunload for that I need to submit the form and nothing should be happen when selected no.

Any help is greaty appreciated

I have tried this

window.onbeforeunload= function(){
    var r = confirm("Are you sure you want to leave this page?");
    if (r == true) {
        readForm.action = '/SREPS/read.do' ;
        readForm.submit();
    }else{
        return false;
    }
}

It did not worked 100% when ever we hit Cancel during window.confirm another dialog appears saying that message from webpage false asking for confirmation leave this page and stay on this page. In this case if the user selects leave this page. I am not able to submit the form.


回答1:


You cannot use your own dialog in onbeforeunload. The only thing you can do is return a string to be displayed (on some browsers). You cannot stop the browser from leaving, only the user can control that.

What you can do is the following:

window.onbeforeunload = function(){
    return 'Are you sure you want to leave this page?';
};

This will ask the user if they want to leave or not. Then you can use the onunload event to run a function when they leave. From there, you can make a "synchronous" AJAX request to submit the form.

window.onunload = function(){
    var request = new XMLHttpRequest();
    request.open('POST', '/SREPS/read.do', false);
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    request.send(new FormData(readForm));
};

If you are using jQuery, you can do:

window.onunload = function(){
    $.ajax({
        url: '/SREPS/read.do',
        type: 'post',
        async: false,
        data: $(readForm).serialize()
    });
};


来源:https://stackoverflow.com/questions/23522652/capture-the-result-of-window-onbeforeunload

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