Skip to content

Commit

Permalink
feat: add multi-tab state change notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
hf committed Dec 22, 2022
1 parent 2b65646 commit cabbc40
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ export default class GoTrueClient {
}
protected fetch: Fetch

/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null = null

/**
* Create a new client for use in the browser.
*/
Expand All @@ -142,6 +147,13 @@ export default class GoTrueClient {
this.fetch = resolveFetch(settings.fetch)
this.detectSessionInUrl = settings.detectSessionInUrl

if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey)
this.broadcastChannel.addEventListener('message', (event) => {
this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages
})
}

this.initialize()
this.mfa = {
verify: this._verify.bind(this),
Expand Down Expand Up @@ -1024,7 +1036,15 @@ export default class GoTrueClient {
}
}

private _notifyAllSubscribers(event: AuthChangeEvent, session: Session | null) {
private _notifyAllSubscribers(
event: AuthChangeEvent,
session: Session | null,
broadcast: boolean = true
) {
if (this.broadcastChannel && broadcast) {
this.broadcastChannel.postMessage({ event, session })
}

this.stateChangeEmitters.forEach((x) => x.callback(event, session))
}

Expand Down

0 comments on commit cabbc40

Please sign in to comment.