Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.