Skip to content

Commit

Permalink
fix: it finally works
Browse files Browse the repository at this point in the history
  • Loading branch information
coolsoftwaretyler committed Oct 30, 2024
1 parent 18cbd77 commit c9f6338
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 55 deletions.
51 changes: 35 additions & 16 deletions src/shells/webextension/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@ import initBackend from '../../backend';
import Bridge from '../../Bridge';
import debugConnection from '../../utils/debugConnection';

console.log('All imports successful');

const backendId = Math.random().toString(32).slice(2);
console.log('Generated backendId:', backendId);

function handshake(hook, contentScriptId) {
console.log('Handshake called with:', { hook, contentScriptId });
let listeners = [];

const bridge = new Bridge({
listen(fn) {
console.log('Bridge listen called');
const listener = evt => {
if (
evt.data.source === 'mobx-devtools-content-script' &&
Expand All @@ -29,6 +34,7 @@ function handshake(hook, contentScriptId) {
window.addEventListener('message', listener);
},
send(data) {
console.log('Bridge send called with:', data);
debugConnection('[BACKEND -> contentScript]', data);
window.postMessage(
{
Expand All @@ -42,30 +48,43 @@ function handshake(hook, contentScriptId) {
},
});

const disposeBackend = initBackend(bridge, hook);

bridge.once('disconnect', () => {
debugConnection('[contentScript -x BACKEND]');
listeners.forEach(listener => window.removeEventListener('message', listener));
listeners = [];
disposeBackend();
});
console.log('Bridge created');

try {
console.log('About to call initBackend');
const disposeBackend = initBackend(bridge, hook);
console.log('initBackend called successfully');
bridge.once('disconnect', () => {
debugConnection('[contentScript -x BACKEND]');
listeners.forEach(listener => window.removeEventListener('message', listener));
listeners = [];
disposeBackend();
});

console.log('MobX DevTools hook status:', {
hook: !!window.__MOBX_DEVTOOLS_GLOBAL_HOOK__,
collections: window.__MOBX_DEVTOOLS_GLOBAL_HOOK__.collections,
});
} catch (e) {
console.error('Error in initBackend:', e);
}
}

/*
This mechanism ensures that each content-script can be messaging with only one backend
and vice versa:
1. Wait for `ping`
2. As soon as pinged, stop listening to `ping` send `pong`,
start waiting for `hello`/`connection-fail`
3. If received `hello`, the connection is established,
if recieved `connection-fail`, then content-script is already busy, return to paragraph 1
*/
This mechanism ensures that each content-script can be messaging with only one backend
and vice versa:
1. Wait for `ping`
2. As soon as pinged, stop listening to `ping` send `pong`,
start waiting for `hello`/`connection-fail`
3. If received `hello`, the connection is established,
if recieved `connection-fail`, then content-script is already busy, return to paragraph 1
*/

function waitForPing() {
function pingListener(evt) {
console.log('[contentScript -> BACKEND]', evt);
if (evt.data.source === 'mobx-devtools-content-script' && evt.data.payload === 'backend:ping') {
console.log('Backend handling ping message');
debugConnection('[contentScript -> BACKEND]', evt);
const { contentScriptId } = evt.data;

Expand Down
1 change: 1 addition & 0 deletions src/shells/webextension/panel.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const inject = done => {
.executeScript({
target: { tabId },
files: ['/backend.js'],
world: 'MAIN',
})
.then(() => {
console.log('Backend script injected');
Expand Down
98 changes: 59 additions & 39 deletions src/shells/webextension/window.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,48 +21,68 @@ const whenTabLoaded = (tabId, cb) => {
const inject = (contentTabId, done) =>
whenTabLoaded(contentTabId, () => {
console.log('Injecting content script');
const code = `
// the prototype stuff is in case document.createElement has been modified
var script = document.constructor.prototype.createElement.call(document, 'script');
script.src = "${chrome.runtime.getURL('backend.js')}";
document.documentElement.appendChild(script);
script.parentNode.removeChild(script);
`;
chrome.tabs.executeScript(contentTabId, { code }, () => {
console.log('Content script injected');
let disconnected = false;

const port = chrome.runtime.connect({
name: `${contentTabId}`,
});
// First inject content script
chrome.scripting
.executeScript({
target: { tabId: contentTabId },
files: ['/contentScript.js'],
})
.then(() => {
console.log('Content script injected');
// Wait a bit for content script to initialize
setTimeout(() => {
// Then inject backend
chrome.scripting
.executeScript({
target: { tabId: contentTabId },
files: ['/backend.js'],
world: 'MAIN',
})
.then(() => {
console.log('Backend script injected');
let disconnected = false;

port.onDisconnect.addListener(() => {
console.log('Port disconnected');
debugConnection('[background -x FRONTEND]');
disconnected = true;
if (onDisconnect) {
onDisconnect();
}
});
const port = chrome.runtime.connect({
name: `${contentTabId}`,
});

const wall = {
listen(fn) {
console.log('Listening for messages');
port.onMessage.addListener(message => {
console.log('Received message:', message);
debugConnection('[background -> FRONTEND]', message);
fn(message);
});
},
send(data) {
if (disconnected) return;
console.log('Sending message:', data);
debugConnection('[FRONTEND -> background]', data);
port.postMessage(data);
},
};
done(wall, () => port.disconnect());
});
port.onDisconnect.addListener(() => {
console.log('Port disconnected');
debugConnection('[background -x FRONTEND]');
disconnected = true;
if (onDisconnect) {
onDisconnect();
}
});

const wall = {
listen(fn) {
console.log('Listening for messages');
port.onMessage.addListener(message => {
console.log('Received message:', message);
debugConnection('[background -> FRONTEND]', message);
fn(message);
});
},
send(data) {
if (disconnected) return;
console.log('Sending message:', data);
debugConnection('[FRONTEND -> background]', data);
port.postMessage(data);
},
};

done(wall, () => port.disconnect());
})
.catch(err => {
console.error('Failed to inject backend:', err);
});
}, 100);
})
.catch(err => {
console.error('Failed to inject content script:', err);
});
});

chrome.runtime.getBackgroundPage(({ contentTabId }) =>
Expand Down

0 comments on commit c9f6338

Please sign in to comment.