v149 · BFCache · WebSocket
Reconnect on Restore
Chrome 149 closes your WebSocket when the page is stored in BFCache. The right response: detect the restore via pageshow.persisted and open a fresh connection automatically. This demo implements and visualises that pattern.
Not connected
page & connection lifecycle log
0 events
—Waiting for connection…idle
the reconnect pattern
1
Open WS on page load: const ws = new WebSocket(url)
2
Listen for pagehide — Chrome will close the socket; you can log it.
3
Listen for pageshow. Check event.persisted === true to detect a BFCache restore.
4
On restore, reconnect: ws = new WebSocket(url). One extra line; the rest of your code is unchanged.
let ws = null;
function wsEndpoint() {
const wsUrl = new URL('/v149/disconnect-websockets-on-bfcache-entry/ws', location.href);
wsUrl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
return wsUrl;
}
function connect() {
ws = new WebSocket(wsEndpoint());
ws.addEventListener('open', () => console.log('connected'));
ws.addEventListener('close', () => console.log('closed'));
}
// Initial connection
connect();
// BFCache restore: reconnect
window.addEventListener('pageshow', (e) => {
if (e.persisted) {
// Page was restored from BFCache; socket was auto-closed by Chrome 149
console.log('BFCache restore detected — reconnecting');
connect();
}
});
window.addEventListener('pagehide', () => {
// Chrome 149 closes the socket here automatically;
// you don't need to call ws.close() yourself
console.log('pagehide: Chrome will close the WS for BFCache');
});
see also
- Connection Lifecycle Observer — watch the full event stream
- BFCache Eligibility Checker — inspect page eligibility
- Feature index
implementation reference
Need the exact API surface, compatibility boundaries, errors, lifecycle, and source links? Read the matching gendn reference ↗