Skip to content

Instantly share code, notes, and snippets.

@maccman
Last active July 3, 2022 08:17
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save maccman/5674933 to your computer and use it in GitHub Desktop.
Save maccman/5674933 to your computer and use it in GitHub Desktop.
jQuery plugin to notify users if they close the page, and there are still some Ajax requests pending.
$ = jQuery
TRANSFORM_TYPES = ['PUT', 'POST', 'DELETE']
$.activeTransforms = 0
$(document).ajaxSend (e, xhr, settings) ->
return unless settings.type in TRANSFORM_TYPES
$.activeTransforms += 1
$(document).ajaxComplete (e, xhr, settings) ->
return unless settings.type in TRANSFORM_TYPES
$.activeTransforms -= 1
window.onbeforeunload or= ->
if $.activeTransforms
'''There are some pending network requests which
means closing the page may lose unsaved data.'''
(function(){
var $ = jQuery;
var TRANSFORM_TYPES = ['PUT', 'POST', 'DELETE'];
$.activeTransforms = 0;
$(document).ajaxSend(function(e, xhr, settings) {
if (TRANSFORM_TYPES.indexOf.call(settings.type) < 0) return;
return $.activeTransforms += 1;
});
$(document).ajaxComplete(function(e, xhr, settings) {
if (TRANSFORM_TYPES.indexOf.call(settings.type) < 0) return;
return $.activeTransforms -= 1;
});
window.onbeforeunload || (window.onbeforeunload = function() {
if ($.activeTransforms) {
return 'There are some pending network requests which\nmeans closing the page may lose unsaved data.';
}
});
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment