Normally, to do connection recovery (that is, automatically resume a connection over a page refresh in ably-js), you just need to set recover: (_, cb) => cb(true)
in the client options.
However, this stores the recovery key in sessionStorage under a fixed session storage key name. session storage is scoped to the origin, so this will not work if you have multiple ably-js sessions under the same origin, and want to use recover on all of them.
Instead, you can do something like the following, manually storing the recovery key yourself under a session storage key name specific to each particular sdk context:
const clientOpts = {
closeOnUnload: false, // stop the connection being closed serverside when the page closes
... // auth opts etc
};
// use a sessionstorage key for this particular context. for example if you have two sdks
// being run in different iframes on the same origin, e.g. one for main page and one for
// a sidebar, the key should be specific to each. It is important that you do not try and
// recover multiple SDK instances from a single recovery key; the resulting behaviour will
// be undefined.
const sessionStorageKey = 'ably-sdk-recoverykey-for-mainpage'
// recover from a previous session, if one exists
const previousSessionRecoveryKey = sessionStorage.getItem(sessionStorageKey);
sessionStorage.removeItem(sessionStorageKey);
if (previousSessionRecoveryKey) {
clientOpts.recover = previousSessionRecoveryKey;
}
const client = new Ably.Realtime(clientOpts);
// store session recovery data when the beforeunload event tells you the tab is being
// closed or refreshed (or based on any other trigger appropriate for the usecase)
window.addEventListener('beforeunload', () => {
const recoveryKey = client.connection.createRecoveryKey();
sessionStorage.setItem(sessionStorageKey, recoveryKey);
});