JSFiddle - React, Tailwind, and code Playground
by pmorch
HTML
<div id="result">Running AJAX request...</div>
<a href="http://www.morch.com">link somewhere click me to generate an error</a>
JavaScript
// The isBeforeunloadSupported() function is described in detail in http://jsfiddle.net/pmorch/tW827/ - see further down for how it is used in dealing with ajax requests.
(function($, global) {
var field = 'beforeunloadSupported';
if (global.localStorage &&
global.localStorage.getItem &&
global.localStorage.setItem &&
! global.localStorage.getItem(field)) {
$(window).on('beforeunload', function () {
global.localStorage.setItem(field, 'yes');
});
$(window).on('unload', function () {
// If unload fires, and beforeunload hasn't set the field,
// then beforeunload didn't fire and is therefore not
// supported (cough * iPad * cough)
if (! global.localStorage.getItem(field)) {
global.localStorage.setItem(field, 'no');
}
});
}
global.isBeforeunloadSupported = function () {
if (global.localStorage &&
global.localStorage.getItem &&
global.localStorage.getItem(field) &&
global.localStorage.getItem(field) == "yes" ) {
return true;
} else {
return false;
}
}
})(jQuery, window);
var beforeunloadCalled = false;
// Beware that 'beforeunload' is not supported in all browsers.
// iPad / iPhone - I'm looking at you.
$(window).on('beforeunload', function () {
beforeunloadCalled = true;
});
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
json: JSON.stringify({
a: 23
}),
delay: 30
},
cache: false,
success: function (json) {
$('#result').text(JSON.stringify(json));
},
error: function () {
if (isBeforeunloadSupported()) {
if (! beforeunloadCalled) {
alert("An error occurred - handling immediately");
}
} else {
setTimeout(function () {
alert("An error occurred - handling in 1...