Problem submitting form on window.unload

后端 未结 2 1788
耶瑟儿~
耶瑟儿~ 2021-01-16 10:03

I am having a problem submitting form on window unload if form information has been updated (album.updated = true):

window.onunload = function(evnt) {
  if (album         


        
相关标签:
2条回答
  • 2021-01-16 10:44

    You don't get to do anything much on unload. At one time more was allowed, but bad sites used to trap and confuse the user, so this has been locked down.

    The only interaction you can get is through onbeforeunload. And you can't reliably prompt to save here either... you aren't generally allowed to circumvent the navigation by submitting the form directly. You can try posting the save request using XMLHttpRequest, but there is no guarantee it will reach the server before the page navigates away.

    So all you can reasonably do is alert the user to the unsaved data, prompting them to cancel the navigation and save the data themselves:

    window.onbeforeunload= function() {
        if (album.updated)
            return (
                'You have unsaved changes to this album. Are you sure you wish '+
                'to leave without saving?'
            );
    };
    
    0 讨论(0)
  • 2021-01-16 10:50

    You cannot reliably interact with the server from the unload event.

    Sending an AJAX request might be a little more reliable, but should also not be relied on.

    Instead, you should handle the onbeforeunload event and return "You have unsaved changes";.
    This will instruct the browser to show a confirmation dialog allowing the user to cancel the navigation. (After which he can save manually)

    0 讨论(0)
提交回复
热议问题