开发者

Run one last Ajax Request on (Back button, forward button, close tab/browser) [duplicate]

This question already has answer开发者_C百科s here: JavaScript, browsers, window close - send an AJAX request or run a script on window closing (9 answers) Closed 6 years ago.

When a user wants to edit a task the file gets locked. When they save or hit the close button(from the dialog) the file gets unlocked.

However if the user clicks any of these : Back button, forward button, close tab/browser

the file is locked. I have a cleanup scheduler that unlocks all files after X minutes.

However I would love to be able to do one last request to unlock the file so people don't have to wait X minutes till the task unlocks itself becasue someone decided shut their browser down.

I found this

$(window).unload(function ()
    {
        alert('unloaded');
    });

However I have no clue what browser it supports or if it does everything I require it to do.


window.onunload = function () {
   // has to be synchronous so the function doesn't return immediately
   $.ajax({
      async: false, 
      ...
   });
};

Synchronous requests aren't looked upon too highly because they can freeze the UI, but I don't see any other way if you want to implement this specific behavior. I'm sure you could do it several other ways without requiring a synchronous request however.

For example, you could ask the user to save the file when they attempt to close the window:

// use beforeunload to prompt the user
window.onbeforeunload = function () {
   if (!saved) {
       return "Please save the task before exiting!";
   }
};

Also, most browsers support these events. I think Opera is an exception though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜