Skip to content

Commit b78c030

Browse files
committed
Fixes for #285 : Unsubscribe on beforeunload instead on unload has Chrome will stop firing unload events
1 parent 4a9e849 commit b78c030

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

modules/javascript/src/main/webapp/javascript/atmosphere.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
var _beforeUnloadState = false;
5353

5454
var atmosphere = {
55-
version: "4.0.1",
55+
version: "4.0.2",
5656
onError: function (response) {
5757
},
5858
onClose: function (response) {
@@ -204,6 +204,7 @@
204204
maxWebsocketErrorRetries: 1,
205205
curWebsocketErrorRetries: 0,
206206
unloadBackwardCompat: !navigator.sendBeacon,
207+
useBeforeUnloadForCleanup: true,
207208
id: undefined,
208209
openId: undefined,
209210
reconnectId: undefined,
@@ -3431,7 +3432,13 @@
34313432
atmosphere.callbacks = {
34323433
unload: function () {
34333434
atmosphere.util.debug(new Date() + " Atmosphere: " + "unload event");
3434-
atmosphere.unsubscribe();
3435+
// Check if we should use the old unload behavior or if beforeunload hasn't handled cleanup
3436+
var shouldCleanupInUnload = requests.length > 0 &&
3437+
(requests[0].request.useBeforeUnloadForCleanup === false || !_beforeUnloadState);
3438+
3439+
if (shouldCleanupInUnload) {
3440+
atmosphere.unsubscribe();
3441+
}
34353442
},
34363443
beforeUnload: function () {
34373444
atmosphere.util.debug(new Date() + " Atmosphere: " + "beforeunload event");
@@ -3443,6 +3450,17 @@
34433450

34443451
// ATMOSPHERE-JAVASCRIPT-143: Delay reconnect to avoid reconnect attempts before an actual unload (we don't know if an unload will happen, yet)
34453452
_beforeUnloadState = true;
3453+
3454+
// Check if we should cleanup in beforeunload (default behavior for better bfcache compatibility)
3455+
var shouldCleanupInBeforeUnload = requests.length > 0 &&
3456+
requests[0].request.useBeforeUnloadForCleanup !== false;
3457+
3458+
if (shouldCleanupInBeforeUnload) {
3459+
// Primary cleanup now happens here instead of in unload event
3460+
// This ensures compatibility with Chrome's bfcache and follows modern best practices
3461+
atmosphere.unsubscribe();
3462+
}
3463+
34463464
atmosphere._beforeUnloadTimeoutId = setTimeout(function () {
34473465
atmosphere.util.debug(new Date() + " Atmosphere: " + "beforeunload event timeout reached. Reset _beforeUnloadState flag");
34483466
_beforeUnloadState = false;

0 commit comments

Comments
 (0)