Skip to content

Commit 4bccc0f

Browse files
authored
Merge pull request #33 from oslabs-beta/feature/garrett
reverted disconnection changes to background and content script
2 parents ea92b93 + 1d5454b commit 4bccc0f

File tree

4 files changed

+22
-134
lines changed

4 files changed

+22
-134
lines changed

src/app/containers/ErrorContainer.tsx

Lines changed: 4 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import React, { useEffect } from 'react';
1+
import React from 'react';
22
import { useDispatch, useSelector } from 'react-redux';
3-
import { launchContentScript, setTab } from '../slices/mainSlice';
3+
import { launchContentScript } from '../slices/mainSlice';
44
import { MainState, RootState, ErrorContainerProps } from '../FrontendTypes';
55
import { RefreshCw, Github, PlayCircle } from 'lucide-react';
66

@@ -10,72 +10,12 @@ function ErrorContainer(props: ErrorContainerProps): JSX.Element {
1010
(state: RootState) => state.main,
1111
);
1212

13-
// Add effect to initialize currentTab if not set
14-
useEffect(() => {
15-
const initializeCurrentTab = async () => {
16-
if (!currentTab) {
17-
try {
18-
// Query for the active tab
19-
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
20-
if (activeTab?.id) {
21-
dispatch(setTab(activeTab.id));
22-
}
23-
} catch (error) {
24-
console.error('Error getting active tab:', error);
25-
}
26-
}
27-
};
28-
29-
initializeCurrentTab();
30-
}, [currentTab, dispatch]);
31-
3213
// function that launches the main app and refreshes the page
3314
function launch(): void {
34-
// Add validation to ensure we have valid data
35-
if (!currentTab) {
36-
console.warn('No current tab available - attempting to get active tab');
37-
// Try to get the active tab when launching
38-
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
39-
if (tabs[0]?.id) {
40-
const activeTabId = tabs[0].id;
41-
dispatch(setTab(activeTabId));
42-
// Create default payload and launch
43-
const defaultPayload = {
44-
status: {
45-
contentScriptLaunched: false,
46-
reactDevToolsInstalled: false,
47-
targetPageisaReactApp: false,
48-
},
49-
};
50-
dispatch(launchContentScript(defaultPayload));
51-
// Allow the dispatch to complete before refreshing
52-
setTimeout(() => {
53-
chrome.tabs.reload(activeTabId);
54-
}, 100);
55-
}
56-
});
57-
return;
58-
}
59-
60-
if (!tabs || !tabs[currentTab]) {
61-
// If no tab data exists, create a minimal valid payload
62-
const defaultPayload = {
63-
status: {
64-
contentScriptLaunched: false,
65-
reactDevToolsInstalled: false,
66-
targetPageisaReactApp: false,
67-
},
68-
};
69-
dispatch(launchContentScript(defaultPayload));
70-
} else {
71-
dispatch(launchContentScript(tabs[currentTab]));
72-
}
73-
15+
dispatch(launchContentScript(tabs[currentTab]));
7416
// Allow the dispatch to complete before refreshing
7517
setTimeout(() => {
76-
if (currentTab) {
77-
chrome.tabs.reload(currentTab);
78-
}
18+
chrome.tabs.reload(currentTab);
7919
}, 100);
8020
}
8121

src/app/containers/MainContainer.tsx

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,12 @@ function MainContainer(): JSX.Element {
4646
}) => {
4747
let maxTab: number;
4848

49-
// Add validation check
5049
if (!sourceTab && action !== 'keepAlive') {
51-
// Ensure payload exists and is an object
52-
if (payload && typeof payload === 'object') {
53-
const tabsArray = Object.keys(payload);
54-
const numTabsArray = tabsArray.map((tab) => Number(tab));
55-
maxTab = numTabsArray.length > 0 ? Math.max(...numTabsArray) : 0;
56-
} else {
57-
console.warn('Invalid payload received:', payload);
58-
maxTab = 0;
59-
}
50+
// if the sourceTab doesn't exist or is 0 and it is not a 'keepAlive' action
51+
const tabsArray: Array<string> = Object.keys(payload); // we create a tabsArray of strings composed of keys from our payload object
52+
const numTabsArray: number[] = tabsArray.map((tab) => Number(tab)); // we then map out our tabsArray where we convert each string into a number
53+
54+
maxTab = Math.max(...numTabsArray); // we then get the largest tab number value
6055
}
6156

6257
switch (action) {
@@ -78,6 +73,7 @@ function MainContainer(): JSX.Element {
7873
}
7974
case 'sendSnapshots': {
8075
dispatch(setTab(payload));
76+
// set state with the information received from the background script
8177
dispatch(addNewSnapshots(payload));
8278
break;
8379
}

src/extension/background.js

Lines changed: 10 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -360,10 +360,13 @@ chrome.runtime.onConnect.addListener(async (port) => {
360360
}
361361

362362
if (Object.keys(tabsObj).length > 0) {
363+
console.log('Sending initial snapshots to devtools:', tabsObj);
363364
port.postMessage({
364365
action: 'initialConnectSnapshots',
365366
payload: tabsObj,
366367
});
368+
} else {
369+
console.log('No snapshots to send to devtools on reconnect.');
367370
}
368371

369372
// Handles port disconnection by removing the disconnected port -ellie
@@ -372,17 +375,6 @@ chrome.runtime.onConnect.addListener(async (port) => {
372375
if (index !== -1) {
373376
console.warn(`Port at index ${index} disconnected. Removing it.`);
374377
portsArr.splice(index, 1);
375-
376-
// Notify remaining ports about the disconnection
377-
portsArr.forEach((remainingPort) => {
378-
try {
379-
remainingPort.postMessage({
380-
action: 'portDisconnect',
381-
});
382-
} catch (error) {
383-
console.warn('Failed to notify port of disconnection:', error);
384-
}
385-
});
386378
}
387379
});
388380

@@ -391,10 +383,6 @@ chrome.runtime.onConnect.addListener(async (port) => {
391383
// (i.e. they're all related to the button actions on Reactime)
392384
port.onMessage.addListener(async (msg) => {
393385
const { action, payload, tabId } = msg;
394-
console.log(`Received message - Action: ${action}, Payload:`, payload);
395-
if (!payload && ['import', 'setPause', 'jumpToSnap'].includes(action)) {
396-
console.error(`Invalid payload received for action: ${action}`, new Error().stack);
397-
}
398386

399387
switch (action) {
400388
// import action comes through when the user uses the "upload" button on the front end to import an existing snapshot tree
@@ -437,42 +425,13 @@ chrome.runtime.onConnect.addListener(async (port) => {
437425
tabsObj[tabId].mode.paused = payload;
438426
return true; // return true so that port remains open
439427

440-
// Handling the launchContentScript case with proper validation
441-
case 'launchContentScript': {
442-
if (!tabId) {
443-
console.error('No tabId provided for content script injection');
444-
return false;
445-
}
446-
447-
try {
448-
// Validate the tab exists before injecting
449-
chrome.tabs.get(tabId, async (tab) => {
450-
if (chrome.runtime.lastError) {
451-
console.error('Error getting tab:', chrome.runtime.lastError);
452-
return;
453-
}
454-
455-
// Skip injection for chrome:// URLs
456-
if (tab.url?.startsWith('chrome://')) {
457-
console.warn('Cannot inject scripts into chrome:// URLs');
458-
return;
459-
}
460-
461-
try {
462-
await chrome.scripting.executeScript({
463-
target: { tabId: tab.id },
464-
files: ['bundles/content.bundle.js'],
465-
});
466-
console.log('Content script injected successfully');
467-
} catch (err) {
468-
console.error('Error injecting content script:', err);
469-
}
470-
});
471-
} catch (err) {
472-
console.error('Error in launchContentScript:', err);
473-
}
428+
case 'launchContentScript':
429+
//if (tab.url?.startsWith("chrome://")) return undefined;
430+
chrome.scripting.executeScript({
431+
target: { tabId },
432+
files: ['bundles/content.bundle.js'],
433+
});
474434
return true;
475-
}
476435

477436
case 'jumpToSnap':
478437
chrome.tabs.sendMessage(tabId, msg);
@@ -712,6 +671,7 @@ chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
712671
payload: tabsObj,
713672
sourceTab,
714673
});
674+
console.log(`Sent snapshots to port at index ${index}`);
715675
} catch (error) {
716676
console.warn(`Failed to send snapshots to port at index ${index}:`, error);
717677
}

src/extension/contentScript.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,17 +73,9 @@ chrome.runtime.onMessage.addListener((request) => {
7373
// '*' == target window origin required for event to be dispatched, '*' = no preference
7474
window.postMessage(request, '*');
7575
}
76-
if (action === 'portDisconnect') {
77-
// When we receive a port disconnection message, relay it to the window
78-
window.postMessage(
79-
{
80-
action: 'portDisconnect',
81-
},
82-
'*',
83-
);
8476

85-
// Attempt to re-establish connection
86-
establishConnection();
77+
// JR: adding a response to a port disconnection message from background.js
78+
if (action === 'portDisconnect') {
8779
}
8880

8981
if (action === 'reinitialize') {

0 commit comments

Comments
 (0)