Merge pull request #229 from sompylasar/217-workaround-disconnected-port-error

Fix for 'Attempting to use a disconnected port object'
This commit is contained in:
Brian Vaughn
2019-04-30 09:15:52 -07:00
committed by GitHub
8 changed files with 87 additions and 23 deletions
+5 -7
View File
@@ -24,8 +24,6 @@ function setup(hook) {
const Bridge = require('src/bridge').default;
const { initBackend } = require('src/backend');
const listeners = [];
const bridge = new Bridge({
listen(fn) {
const listener = event => {
@@ -39,8 +37,10 @@ function setup(hook) {
}
fn(event.data.payload);
};
listeners.push(listener);
window.addEventListener('message', listener);
return () => {
window.removeEventListener('message', listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
window.postMessage(
@@ -56,11 +56,9 @@ function setup(hook) {
const agent = new Agent(bridge);
agent.addListener('shutdown', () => {
// If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down,
// and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here.
hook.emit('shutdown');
listeners.forEach(fn => {
window.removeEventListener('message', fn);
});
listeners.splice(0);
});
initBackend(hook, agent, window);
+12 -9
View File
@@ -46,22 +46,24 @@ function createPanelIfReactLoaded() {
let root = null;
function initBridgeAndStore() {
let hasPortBeenDisconnected = false;
const port = chrome.runtime.connect({
name: '' + chrome.devtools.inspectedWindow.tabId,
});
port.onDisconnect.addListener(() => {
hasPortBeenDisconnected = true;
});
// Looks like `port.onDisconnect` does not trigger on in-tab navigation like new URL or back/forward navigation,
// so it makes no sense to handle it here.
bridge = new Bridge({
listen(fn) {
port.onMessage.addListener(message => fn(message));
const listener = message => fn(message);
// Store the reference so that we unsubscribe from the same object.
const portOnMessage = port.onMessage;
portOnMessage.addListener(listener);
return () => {
portOnMessage.removeListener(listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
if (!hasPortBeenDisconnected) {
port.postMessage({ event, payload }, transferable);
}
port.postMessage({ event, payload }, transferable);
},
});
bridge.addListener('reloadAppForProfiling', () => {
@@ -270,7 +272,8 @@ function createPanelIfReactLoaded() {
// Shutdown bridge and re-initialize DevTools panel when a new page is loaded.
chrome.devtools.network.onNavigated.addListener(function onNavigated() {
bridge.send('shutdown');
// `bridge.shutdown()` will remove all listeners we added, so we don't have to.
bridge.shutdown();
// It's easiest to recreate the DevTools panel (to clean up potential stale state).
// We can revisit this in the future as a small optimization.