|
205 | 205 | curWebsocketErrorRetries: 0, |
206 | 206 | unloadBackwardCompat: !navigator.sendBeacon, |
207 | 207 | useBeforeUnloadForCleanup: true, |
| 208 | + usePageHide: true, |
208 | 209 | id: undefined, |
209 | 210 | openId: undefined, |
210 | 211 | reconnectId: undefined, |
|
3466 | 3467 | _beforeUnloadState = false; |
3467 | 3468 | }, 5000); |
3468 | 3469 | }, |
| 3470 | + pageHide: function (event) { |
| 3471 | + atmosphere.util.debug(new Date() + " Atmosphere: pagehide event"); |
| 3472 | + |
| 3473 | + // Only cleanup if page is being persisted to bfcache or actually unloading |
| 3474 | + // event.persisted indicates if page is entering bfcache |
| 3475 | + if (requests.length > 0) { |
| 3476 | + atmosphere.unsubscribe(); |
| 3477 | + } |
| 3478 | + }, |
3469 | 3479 | offline: function () { |
3470 | 3480 | atmosphere.util.debug(new Date() + " Atmosphere: offline event"); |
3471 | 3481 | offline = true; |
|
3499 | 3509 | }; |
3500 | 3510 |
|
3501 | 3511 | atmosphere.bindEvents = function () { |
3502 | | - atmosphere.util.on(window, "unload", atmosphere.callbacks.unload); |
3503 | | - atmosphere.util.on(window, "beforeunload", atmosphere.callbacks.beforeUnload); |
| 3512 | + var request = requests.length > 0 ? requests[0].request : {}; |
| 3513 | + |
| 3514 | + // Use pagehide as the default modern approach (doesn't block bfcache) |
| 3515 | + if (request.usePageHide !== false && 'onpagehide' in window) { |
| 3516 | + atmosphere.util.on(window, "pagehide", atmosphere.callbacks.pageHide); |
| 3517 | + } |
| 3518 | + // Fallback to beforeunload if pagehide is disabled or not supported |
| 3519 | + else if (request.useBeforeUnloadForCleanup !== false) { |
| 3520 | + atmosphere.util.on(window, "beforeunload", atmosphere.callbacks.beforeUnload); |
| 3521 | + } |
| 3522 | + // Legacy unload event only if both modern options are disabled |
| 3523 | + else { |
| 3524 | + atmosphere.util.on(window, "unload", atmosphere.callbacks.unload); |
| 3525 | + } |
| 3526 | + |
3504 | 3527 | atmosphere.util.on(window, "offline", atmosphere.callbacks.offline); |
3505 | 3528 | atmosphere.util.on(window, "online", atmosphere.callbacks.online); |
3506 | 3529 | }; |
3507 | 3530 |
|
3508 | 3531 | atmosphere.unbindEvents = function () { |
3509 | | - atmosphere.util.off(window, "unload", atmosphere.callbacks.unload); |
| 3532 | + // Unbind all possible unload-related events to ensure proper cleanup |
| 3533 | + atmosphere.util.off(window, "pagehide", atmosphere.callbacks.pageHide); |
3510 | 3534 | atmosphere.util.off(window, "beforeunload", atmosphere.callbacks.beforeUnload); |
| 3535 | + atmosphere.util.off(window, "unload", atmosphere.callbacks.unload); |
3511 | 3536 | atmosphere.util.off(window, "offline", atmosphere.callbacks.offline); |
3512 | 3537 | atmosphere.util.off(window, "online", atmosphere.callbacks.online); |
3513 | 3538 | }; |
|
0 commit comments