Port name details (#667)

* Use a stringified JSON details object for extension port names

* Fix incorrect frame ID check

* Add support for connecting to different tabs

* Add function for invoking on a different tab
This commit is contained in:
toasted-nutbread 2020-07-18 14:16:35 -04:00 committed by GitHub
parent dac33e6961
commit a13a68990e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 89 additions and 34 deletions

View File

@ -305,20 +305,32 @@ class Backend {
_onConnect(port) { _onConnect(port) {
try { try {
const match = /^background-cross-frame-communication-port-(\d+)$/.exec(`${port.name}`); let details;
if (match === null) { return; } try {
details = JSON.parse(port.name);
} catch (e) {
return;
}
if (details.name !== 'background-cross-frame-communication-port') { return; }
const tabId = (port.sender && port.sender.tab ? port.sender.tab.id : null); const tabId = (port.sender && port.sender.tab ? port.sender.tab.id : null);
if (typeof tabId !== 'number') { if (typeof tabId !== 'number') {
throw new Error('Port does not have an associated tab ID'); throw new Error('Port does not have an associated tab ID');
} }
const senderFrameId = port.sender.frameId; const senderFrameId = port.sender.frameId;
if (typeof tabId !== 'number') { if (typeof senderFrameId !== 'number') {
throw new Error('Port does not have an associated frame ID'); throw new Error('Port does not have an associated frame ID');
} }
const targetFrameId = parseInt(match[1], 10); let {targetTabId, targetFrameId} = details;
if (typeof targetTabId !== 'number') {
targetTabId = tabId;
}
let forwardPort = chrome.tabs.connect(tabId, {frameId: targetFrameId, name: `cross-frame-communication-port-${senderFrameId}`}); const details2 = {
name: 'cross-frame-communication-port',
sourceFrameId: senderFrameId
};
let forwardPort = chrome.tabs.connect(targetTabId, {frameId: targetFrameId, name: JSON.stringify(details2)});
const cleanup = () => { const cleanup = () => {
this._checkLastError(chrome.runtime.lastError); this._checkLastError(chrome.runtime.lastError);
@ -720,9 +732,12 @@ class Backend {
const frameId = sender.frameId; const frameId = sender.frameId;
const id = yomichan.generateId(16); const id = yomichan.generateId(16);
const portName = `action-port-${id}`; const details = {
name: 'action-port',
id
};
const port = chrome.tabs.connect(tabId, {name: portName, frameId}); const port = chrome.tabs.connect(tabId, {name: JSON.stringify(details), frameId});
try { try {
this._createActionListenerPort(port, sender, this._messageHandlersWithProgress); this._createActionListenerPort(port, sender, this._messageHandlersWithProgress);
} catch (e) { } catch (e) {
@ -730,7 +745,7 @@ class Backend {
throw e; throw e;
} }
return portName; return details;
} }
async _onApiImportDictionaryArchive({archiveContent, details}, sender, onProgress) { async _onApiImportDictionaryArchive({archiveContent, details}, sender, onProgress) {

View File

@ -212,16 +212,13 @@ const api = (() => {
_createActionPort(timeout=5000) { _createActionPort(timeout=5000) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let timer = null; let timer = null;
const { const portDetails = deferPromise();
promise: portNamePromise,
resolve: portNameResolve,
reject: portNameReject
} = deferPromise();
const onConnect = async (port) => { const onConnect = async (port) => {
try { try {
const portName = await portNamePromise; const {name: expectedName, id: expectedId} = await portDetails.promise;
if (port.name !== portName || timer === null) { return; } const {name, id} = JSON.parse(port.name);
if (name !== expectedName || id !== expectedId || timer === null) { return; }
} catch (e) { } catch (e) {
return; return;
} }
@ -239,14 +236,14 @@ const api = (() => {
timer = null; timer = null;
} }
chrome.runtime.onConnect.removeListener(onConnect); chrome.runtime.onConnect.removeListener(onConnect);
portNameReject(e); portDetails.reject(e);
reject(e); reject(e);
}; };
timer = setTimeout(() => onError(new Error('Timeout')), timeout); timer = setTimeout(() => onError(new Error('Timeout')), timeout);
chrome.runtime.onConnect.addListener(onConnect); chrome.runtime.onConnect.addListener(onConnect);
this._invoke('createActionPort').then(portNameResolve, onError); this._invoke('createActionPort').then(portDetails.resolve, onError);
}); });
} }

View File

@ -16,8 +16,9 @@
*/ */
class CrossFrameAPIPort extends EventDispatcher { class CrossFrameAPIPort extends EventDispatcher {
constructor(otherFrameId, port, messageHandlers) { constructor(otherTabId, otherFrameId, port, messageHandlers) {
super(); super();
this._otherTabId = otherTabId;
this._otherFrameId = otherFrameId; this._otherFrameId = otherFrameId;
this._port = port; this._port = port;
this._messageHandlers = messageHandlers; this._messageHandlers = messageHandlers;
@ -26,6 +27,10 @@ class CrossFrameAPIPort extends EventDispatcher {
this._eventListeners = new EventListenerCollection(); this._eventListeners = new EventListenerCollection();
} }
get otherTabId() {
return this._otherTabId;
}
get otherFrameId() { get otherFrameId() {
return this._otherFrameId; return this._otherFrameId;
} }
@ -211,8 +216,12 @@ class CrossFrameAPI {
chrome.runtime.onConnect.addListener(this._onConnect.bind(this)); chrome.runtime.onConnect.addListener(this._onConnect.bind(this));
} }
async invoke(targetFrameId, action, params={}) { invoke(targetFrameId, action, params={}) {
const commPort = this._getOrCreateCommPort(targetFrameId); return this.invokeTab(null, targetFrameId, action, params);
}
async invokeTab(targetTabId, targetFrameId, action, params={}) {
const commPort = this._getOrCreateCommPort(targetTabId, targetFrameId);
return await commPort.invoke(action, params, this._ackTimeout, this._responseTimeout); return await commPort.invoke(action, params, this._ackTimeout, this._responseTimeout);
} }
@ -226,31 +235,65 @@ class CrossFrameAPI {
} }
_onConnect(port) { _onConnect(port) {
const match = /^cross-frame-communication-port-(\d+)$/.exec(`${port.name}`); try {
if (match === null) { return; } let details;
try {
details = JSON.parse(port.name);
} catch (e) {
return;
}
if (details.name !== 'cross-frame-communication-port') { return; }
const otherFrameId = parseInt(match[1], 10); const otherTabId = details.sourceTabId;
this._setupCommPort(otherFrameId, port); const otherFrameId = details.sourceFrameId;
this._setupCommPort(otherTabId, otherFrameId, port);
} catch (e) {
port.disconnect();
yomichan.logError(e);
}
} }
_onDisconnect(commPort) { _onDisconnect(commPort) {
commPort.off('disconnect', this._onDisconnectBind); commPort.off('disconnect', this._onDisconnectBind);
this._commPorts.delete(commPort.otherFrameId); const {otherTabId, otherFrameId} = commPort;
const tabPorts = this._commPorts.get(otherTabId);
if (typeof tabPorts !== 'undefined') {
tabPorts.delete(otherFrameId);
if (tabPorts.size === 0) {
this._commPorts.delete(otherTabId);
}
}
} }
_getOrCreateCommPort(otherFrameId) { _getOrCreateCommPort(otherTabId, otherFrameId) {
const commPort = this._commPorts.get(otherFrameId); const tabPorts = this._commPorts.get(otherTabId);
return (typeof commPort !== 'undefined' ? commPort : this._createCommPort(otherFrameId)); if (typeof tabPorts !== 'undefined') {
const commPort = tabPorts.get(otherFrameId);
if (typeof commPort !== 'undefined') {
return commPort;
}
}
return this._createCommPort(otherTabId, otherFrameId);
} }
_createCommPort(otherFrameId) { _createCommPort(otherTabId, otherFrameId) {
const port = yomichan.connect(null, {name: `background-cross-frame-communication-port-${otherFrameId}`}); const details = {
return this._setupCommPort(otherFrameId, port); name: 'background-cross-frame-communication-port',
targetTabId: otherTabId,
targetFrameId: otherFrameId
};
const port = yomichan.connect(null, {name: JSON.stringify(details)});
return this._setupCommPort(otherTabId, otherFrameId, port);
} }
_setupCommPort(otherFrameId, port) { _setupCommPort(otherTabId, otherFrameId, port) {
const commPort = new CrossFrameAPIPort(otherFrameId, port, this._messageHandlers); const commPort = new CrossFrameAPIPort(otherTabId, otherFrameId, port, this._messageHandlers);
this._commPorts.set(otherFrameId, commPort); let tabPorts = this._commPorts.get(otherTabId);
if (typeof tabPorts === 'undefined') {
tabPorts = new Map();
this._commPorts.set(otherTabId, tabPorts);
}
tabPorts.set(otherFrameId, commPort);
commPort.prepare(); commPort.prepare();
commPort.on('disconnect', this._onDisconnectBind); commPort.on('disconnect', this._onDisconnectBind);
return commPort; return commPort;