Skip to content

Instantly share code, notes, and snippets.

@rony-arnac
Created January 18, 2023 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rony-arnac/3e271d654ad123b12217106b8cb10d0d to your computer and use it in GitHub Desktop.
Save rony-arnac/3e271d654ad123b12217106b8cb10d0d to your computer and use it in GitHub Desktop.
retry establishing connection when the background service worker restarts
// Background service worker
function backgroundServiceHandshake() {
chrome.runtime.onMessage.addListener((message: any, _: any, sendResponse: (response: 'ack') => void) => {
if (message === 'syn') {
if (!isInitialized) {
initializeService();
isInitialized = true;
}
sendResponse('ack');
}
// Otherwise, the message is irrelevant and ignored
});
}
// Other service -- either Popup or DApp
let otherServicePort = chrome.runtime.connect({ name }) as RuntimePort;
const messageQueue: any[] = [];
// Reconnect on disconnecting from background
port.onDisconnect.addListener(() => {
port = chrome.runtime.connect({ name: this.name }) as RuntimePort;
isBackgroundServiceListening = false;
// Retry handshake
otherServiceHandshake();
});
function otherServiceSender(data: any) {
if (isBackgroundServiceListening) {
otherServicePort.postMessage(data);
} else {
// If background is down, queue messages
messageQueue.push(data);
}
}
function sendPendingMessages() {
// Empty pending messages' queue
if (messageQueue.length > 0) {
const currMessageQueue = messageQueue.splice(0, messageQueue.length);
for (const message of currMessageQueue) {
otherServiceSender(message);
}
}
}
function otherServiceHandshake() {
chrome.runtime.sendMessage('syn', (message: any) => {
if (message === 'ack') {
// Send queued messages
sendPendingMessages();
isBackgroundServiceListening = true;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment