import { Message, MessageType, } from '../communication'; const connections = new Map(); /// A queue of messages that were not able to be delivered and will be /// retried when the connection to the content script or extension is /// re-established const messageBuffer = new Map>(); const drainQueue = (port: chrome.runtime.Port, buffer: Array) => { if (buffer == null || buffer.length === 0) { return; } let removed = 0; const send = (m: Message, index: number) => { port.postMessage(m); ++removed; }; try { buffer.forEach(send); } catch (error) { // port disconnected, re-try on connect. } buffer.splice(0, removed); }; chrome.runtime.onMessage.addListener( (message, sender, sendResponse) => { if (message.messageType === MessageType.Initialize) { sendResponse({ // note that this is separate from our message response system extensionId: chrome.runtime.id }); } if (sender.tab) { let sent = false; const connection = connections.get(sender.tab.id); if (connection) { try { connection.postMessage(message); sent = true; } catch (err) {} } if (sent === false) { let queue = messageBuffer.get(sender.tab.id); if (queue == null) { queue = new Array(); messageBuffer.set(sender.tab.id, queue); } queue.push(message); } } return true; }); chrome.runtime.onConnect.addListener(port => { const listener = (message, sender) => { if (connections.has(message.tabId) === false) { connections.set(message.tabId, port); } drainQueue(message.tabId, messageBuffer.get(message.tabId)); chrome.tabs.sendMessage(message.tabId, message); }; port.onMessage.addListener(listener); port.onDisconnect.addListener(() => { port.onMessage.removeListener( listener); connections.forEach((value, key, map) => { if (value === port) { map.delete(key); } }); }); });