/**
* Channel for broadcasting key
*/
const channel = new BroadcastChannel("KEY");
let firstInstance = true;
// all reload generate a new key
let key = generateKey()
channel.onmessage = async (event: MessageEvent<Message>) => {
const message = event.data;
if (message.nature === "newinstance" && firstInstance) {
// only first instance send key
// QUESTION : can first instance disappear
channel.postMessage({ nature: "key", data: key });
}
if (message.nature === "key" && firstInstance) {
// only last instance change
key = message.data;
// it is a new instance
firstInstance = false;
}
};
/**
* All instance post the message
* if 1 instance => no post
* if 2nd instance => only 1st instance receive message => send key
* if 3rd instance => only 1st instance send message because 2nd instance has firstInstance = false
*/
channel.postMessage({ nature: "newinstance" });
/**
* Channel for broadcasting key
*/
const channel = new BroadcastChannel("KEY");
let firstInstance = true;
// all reload generate a new key
let key = generateKey()
channel.onmessage = async (event: MessageEvent<Message>) => {
const message = event.data;
if (message.nature === "newinstance" && firstInstance) {
// only first instance send key
// QUESTION : can first instance disappear
channel.postMessage({ nature: "key", data: key });
}
if (message.nature === "key" && firstInstance) {
// only last instance change
key = message.data;
// it is a new instance
firstInstance = false;
}
};
/**
* All instance post the message
* if 1 instance => no post
* if 2nd instance => only 1st instance receive message => send key
* if 3rd instance => only 1st instance send message because 2nd instance has firstInstance = false
*/
channel.postMessage({ nature: "newinstance" });