Monday, June 4, 2012

Ajax requests are canceled when hitting escape

The default behavior of most browsers is to cancel all ongoing requests when a user hits escape.  Last week this bit us in the foot, as we ‘forgot’ to expect this behavior and requests were never fired again in a single page web app.

The clean solution is of course to implement cancellation logic for all requests, but as the users were waiting for a solution, we introduced a quick fix.

By handling the keydown and keypress event on the document level, we prevented the Escape from bubbling up to the browser and cancelling all requests.

$(document).keypress(function(e) {
if(e.keyCode == 27) {
e.preventDefault();
}
}

$(document).keydown(function(e) {
if(e.keyCode == 27) {
e.preventDefault();
}
}

No comments: