Skip to content

Commit 4d52ba7

Browse files
Christopher StamperChristopher Stamper
authored andcommitted
Added error handling for port connection
1 parent 9f557c8 commit 4d52ba7

File tree

4 files changed

+102
-125
lines changed

4 files changed

+102
-125
lines changed

src/app/RTKslices.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,9 @@ export const mainSlice = createSlice({
116116
},
117117

118118
setPort: (state, action) => {
119+
console.log('port start: ', current(state))
119120
state.port = action.payload;
121+
console.log('port end: ', current(state))
120122
},
121123

122124
setTab: (state, action) => {

src/app/containers/ButtonsContainer.tsx

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -64,35 +64,8 @@ function ButtonsContainer(): JSX.Element {
6464
}
6565

6666
const handleReconnectConfirm = () => {
67-
// const maxRetries = 10;
68-
// const retryInterval = 1000;
69-
// const maxTimeout = 15000
70-
71-
// const attemptReconnection = (retries: number, startTime: number) => {
72-
// console.log('WORKING')
73-
// if (retries <= maxRetries && Date.now() - startTime < maxTimeout) {
74-
// console.log('HITTING IF');
75-
// chrome.runtime.sendMessage({ action: 'attemptReconnect' }, (response) => {
76-
// console.log('response: ', response);
77-
// // if (response && response.success) {
78-
// // console.log('SUCCESS')
79-
// // } else {
80-
// // console.log('Reconnect failed: ', !response && response.success);
81-
82-
// // setTimeout(() => {
83-
// // console.log('trying!')
84-
// // attemptReconnection(retries + 1, startTime);
85-
// // }, retryInterval);
86-
// // }
87-
// });
88-
// } else {
89-
// console.log('Max tries completed');
90-
// }
91-
// }
92-
9367
handleReconnectCancel();
94-
dispatch(startReconnect);
95-
// attemptReconnection(1, Date.now());
68+
dispatch(startReconnect());
9669
}
9770

9871
const handleReconnectCancel = () => {

src/app/containers/MainContainer.tsx

Lines changed: 79 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,9 @@ import {
1515
setCurrentLocation,
1616
disconnected,
1717
endConnect,
18-
launchContentScript,
1918
} from '../RTKslices';
2019
import { useDispatch, useSelector } from 'react-redux';
2120

22-
import { Status } from '../../backend/types/backendTypes';
23-
2421
/*
2522
This is the main container where everything in our application is rendered
2623
*/
@@ -31,10 +28,9 @@ function MainContainer(): JSX.Element {
3128
const currentTab = useSelector((state: any) => state.main.currentTab);
3229
const tabs = useSelector((state: any) => state.main.tabs);
3330
const port = useSelector((state: any) => state.main.port);
34-
const { connectionStatus, connectRequested } = useSelector((state: any) => state.main);
31+
const { connectRequested } = useSelector((state: any) => state.main);
3532

3633
const [actionView, setActionView] = useState(true); // We create a local state 'actionView' and set it to true
37-
const [currentPort, setCurrentPort] = useState(null);
3834

3935
// this function handles Time Jump sidebar view
4036
const toggleActionContainer = () => {
@@ -52,6 +48,9 @@ function MainContainer(): JSX.Element {
5248
}
5349
};
5450

51+
52+
53+
5554
const handleDisconnect = (msg): void => {
5655
if (msg === 'portDisconnect') {
5756
console.log('unexpected port disconnection');
@@ -62,7 +61,7 @@ function MainContainer(): JSX.Element {
6261
const handleConnect = () => {
6362
const maxRetries = 10;
6463
const retryInterval = 1000;
65-
const maxTimeout = 15000
64+
const maxTimeout = 15000;
6665

6766
return new Promise((resolve) => {
6867
let port: chrome.runtime.Port;
@@ -71,8 +70,9 @@ function MainContainer(): JSX.Element {
7170
const attemptReconnection = (retries: number, startTime: number) => {
7271
// console.log('WORKING')
7372
if (retries <= maxRetries && Date.now() - startTime < maxTimeout) {
74-
if (retries === 1) port = chrome.runtime.connect();
75-
console.log('HITTING IF');
73+
if (retries === 1)
74+
port = chrome.runtime.connect();
75+
// console.log('HITTING IF');
7676
chrome.runtime.sendMessage({ action: 'attemptReconnect' }, (response) => {
7777
if (response && response.success) {
7878
console.log('Reconnect Success: ', response.success);
@@ -81,7 +81,7 @@ function MainContainer(): JSX.Element {
8181
console.log('Reconnect failed: ', !response && response.success);
8282

8383
setTimeout(() => {
84-
console.log('trying!')
84+
console.log('trying!', retries)
8585
attemptReconnection(retries + 1, startTime);
8686
}, retryInterval);
8787
}
@@ -95,90 +95,89 @@ function MainContainer(): JSX.Element {
9595
});
9696
}
9797

98+
const messageListener = (message: {
99+
action: string;
100+
payload: Record<string, unknown>;
101+
sourceTab: number
102+
}) => {
103+
const { action, payload, sourceTab } = message;
104+
let maxTab: number;
105+
106+
if (!sourceTab && action !== 'keepAlive') { // if the sourceTab doesn't exist or is 0 and it is not a 'keepAlive' action
107+
const tabsArray: Array<string> = Object.keys(payload); // we create a tabsArray of strings composed of keys from our payload object
108+
const numTabsArray: number[] = tabsArray.map((tab) => Number(tab)); // we then map out our tabsArray where we convert each string into a number
109+
110+
maxTab = Math.max(...numTabsArray); // we then get the largest tab number value
111+
}
112+
113+
switch (action) {
114+
case 'deleteTab': {
115+
dispatch(deleteTab(payload));
116+
break;
117+
}
118+
case 'devTools': {
119+
dispatch(noDev(payload));
120+
break;
121+
}
122+
case 'changeTab': {
123+
console.log('received changeTab message')
124+
dispatch(setTab(payload));
125+
break;
126+
}
127+
case 'sendSnapshots': {
128+
dispatch(setTab(sourceTab));
129+
// set state with the information received from the background script
130+
dispatch(addNewSnapshots(payload));
131+
break;
132+
}
133+
case 'initialConnectSnapshots': {
134+
dispatch(initialConnect(payload));
135+
break;
136+
}
137+
case 'setCurrentLocation': {
138+
dispatch(setCurrentLocation(payload));
139+
break;
140+
}
141+
default:
142+
}
143+
}
144+
98145
useEffect(() => {
99146
if (!connectRequested) return; // only open port once so if it exists, do not run useEffect again
100147

101148
// chrome.runtime allows our application to retrieve our service worker (our eventual bundles/background.bundle.js after running npm run build), details about the manifest, and allows us to listen and respond to events in our application lifecycle.
102149

103150
handleConnect()
104-
.then((port) => {
151+
.then((port: chrome.runtime.Port | null) => {
105152
if (port) {
106153
console.log('PORT SUCCESS: ', port)
107-
setCurrentPort(port);
108-
} else {
109-
console.log('PORT FAIL: ', port);
110-
}
111-
});
112-
113-
console.log('that port tho: ', currentPort);
114-
115-
// listen for a message containing snapshots from the /extension/build/background.js service worker
116-
currentPort.onMessage.addListener(
117-
// parameter message is an object with following type script properties
118-
(message: {
119-
action: string;
120-
payload: Record<string, unknown>;
121-
sourceTab: number
122-
}) => {
123-
const { action, payload, sourceTab } = message;
124-
let maxTab: number;
125-
126-
if (!sourceTab && action !== 'keepAlive') { // if the sourceTab doesn't exist or is 0 and it is not a 'keepAlive' action
127-
const tabsArray: Array<string> = Object.keys(payload); // we create a tabsArray of strings composed of keys from our payload object
128-
const numTabsArray: number[] = tabsArray.map((tab) => Number(tab)); // we then map out our tabsArray where we convert each string into a number
129154

130-
maxTab = Math.max(...numTabsArray); // we then get the largest tab number value
131-
}
132-
133-
switch (action) {
134-
case 'deleteTab': {
135-
dispatch(deleteTab(payload));
136-
break;
137-
}
138-
case 'devTools': {
139-
dispatch(noDev(payload));
140-
break;
141-
}
142-
case 'changeTab': {
143-
dispatch(setTab(payload));
144-
break;
145-
}
146-
case 'sendSnapshots': {
147-
dispatch(setTab(sourceTab));
148-
// set state with the information received from the background script
149-
dispatch(addNewSnapshots(payload));
150-
break;
151-
}
152-
case 'initialConnectSnapshots': {
153-
dispatch(initialConnect(payload));
154-
break;
155-
}
156-
case 'setCurrentLocation': {
157-
dispatch(setCurrentLocation(payload));
158-
break;
159-
}
160-
default:
161-
}
162-
},
163-
);
164-
155+
const currentPort = port;
156+
157+
if (chrome.runtime.onMessage.hasListener(messageListener))
158+
chrome.runtime.onMessage.removeListener(messageListener);
165159

166-
if (chrome.runtime.onMessage.hasListener(handleDisconnect))
167-
chrome.runtime.onMessage.removeListener(handleDisconnect);
168-
169-
// used to track when the above connection closes unexpectedly. Remember that it should persist throughout the application lifecycle
170-
chrome.runtime.onMessage.addListener(handleDisconnect);
160+
// listen for a message containing snapshots from the /extension/build/background.js service worker
161+
currentPort.onMessage.addListener(messageListener);
162+
163+
currentPort.postMessage({ initialized: true });
164+
console.log('posted message');
171165

172-
setTimeout(() => {
173-
currentPort.disconnect();
174-
}, 17000)
166+
if (chrome.runtime.onMessage.hasListener(handleDisconnect))
167+
chrome.runtime.onMessage.removeListener(handleDisconnect);
168+
169+
// used to track when the above connection closes unexpectedly. Remember that it should persist throughout the application lifecycle
170+
chrome.runtime.onMessage.addListener(handleDisconnect);
175171

176-
// assign port to state so it could be used by other components
177-
if (currentPort)
178-
dispatch(setPort(currentPort));
172+
// assign port to state so it could be used by other components
173+
dispatch(setPort(currentPort));
179174

180-
dispatch(endConnect());
181-
});
175+
dispatch(endConnect());
176+
} else {
177+
console.log('PORT FAIL: ', port);
178+
}
179+
});
180+
}, [connectRequested]);
182181

183182
// Error Page launch IF(Content script not launched OR RDT not installed OR Target not React app)
184183
if (

src/extension/background.js

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ function changeCurrLocation(tabObj, rootNode, index, name) {
137137
This allows us to set up listener's for when we connect, message, and disconnect the script.
138138
*/
139139

140+
// let initialized = false;
140141
let portSuccessfullyConnected = false;
141142

142143
// Establishing incoming connection with Reactime.
@@ -165,24 +166,26 @@ chrome.runtime.onConnect.addListener((port) => {
165166
portSuccessfullyConnected = port ? true : false;
166167

167168
portsArr.push(port); // push each Reactime communication channel object to the portsArr
168-
169-
// On Reactime launch: make sure RT's active tab is correct
170-
if (portsArr.length > 0) {
171-
portsArr.forEach((bg) => {// go through each port object (each Reactime instance)
172-
bg.postMessage({ // send passed in action object as a message to the current port
173-
action: 'changeTab',
174-
payload: { tabId: activeTab.id, title: activeTab.title },
175-
})
176-
});
177-
}
178169

179-
// send tabs obj to the connected devtools as soon as connection to devtools is made
180-
if (Object.keys(tabsObj).length > 0) {
181-
port.postMessage({
182-
action: 'initialConnectSnapshots',
183-
payload: tabsObj,
184-
});
185-
}
170+
port.onMessage.addListener((msg) => {
171+
console.log('background message: ', msg);
172+
if (msg.initialized && portsArr.length > 0) {
173+
console.log('sending changeTab message!!!!');
174+
portsArr.forEach((bg) => {// go through each port object (each Reactime instance)
175+
bg.postMessage({ // send passed in action object as a message to the current port
176+
action: 'changeTab',
177+
payload: { tabId: activeTab.id, title: activeTab.title },
178+
})
179+
});
180+
}
181+
if (msg.initialized && Object.keys(tabsObj).length > 0) {
182+
console.log('sending initialConnectSnapshots message!!!!!')
183+
port.postMessage({
184+
action: 'initialConnectSnapshots',
185+
payload: tabsObj,
186+
});
187+
}
188+
});
186189

187190
// every time devtool is closed, remove the port from portsArr
188191
port.onDisconnect.addListener((e) => {

0 commit comments

Comments
 (0)