Created
January 18, 2023 09:55
-
-
Save rony-arnac/3e271d654ad123b12217106b8cb10d0d to your computer and use it in GitHub Desktop.
retry establishing connection when the background service worker restarts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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