Skip to content

Commit e6125c2

Browse files
authored
Merge pull request #18 from oslabs-beta/feature/ellie
Feature/ellie
2 parents 0d2decc + 49a64df commit e6125c2

File tree

3 files changed

+42
-183
lines changed

3 files changed

+42
-183
lines changed

src/extension/background.js

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,28 @@ let activeTab;
1616
const tabsObj = {};
1717
// Will store Chrome web vital metrics and their corresponding values.
1818
const metrics = {};
19+
function setupKeepAlive() {
20+
//ellie
21+
// Create an alarm that triggers every 4.9 minutes (under the 5-minute limit)
22+
chrome.alarms.create('keepAlive', { periodInMinutes: 4.9 });
23+
24+
chrome.alarms.onAlarm.addListener((alarm) => {
25+
if (alarm.name === 'keepAlive') {
26+
console.log('Keep-alive alarm triggered.');
27+
pingServiceWorker();
28+
}
29+
});
30+
}
31+
// Ping the service worker to keep it alive
32+
function pingServiceWorker() {
33+
chrome.runtime.getBackgroundPage((bgPage) => {
34+
if (bgPage) {
35+
console.log('Service worker is alive');
36+
} else {
37+
console.warn('Failed to ping the service worker.');
38+
}
39+
});
40+
}
1941

2042
// function pruning the chrome ax tree and pulling the relevant properties
2143
const pruneAxTree = (axTree) => {
@@ -318,7 +340,18 @@ chrome.runtime.onConnect.addListener(async (port) => {
318340
});
319341
});
320342
}
343+
if (port.name === 'keepAlivePort') {
344+
console.log('Keep-alive port connected:', port);
321345

346+
// Keep the port open by responding to any message
347+
port.onMessage.addListener((msg) => {
348+
console.log('Received message from content script:', msg);
349+
});
350+
351+
port.onDisconnect.addListener(() => {
352+
console.warn('Keep-alive port disconnected.');
353+
});
354+
}
322355
if (portsArr.length > 0 && Object.keys(tabsObj).length > 0) {
323356
//if the activeTab is not set during the onActivate API, run a query to get the tabId and set activeTab
324357
if (!activeTab) {
@@ -723,20 +756,15 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
723756
}
724757
});
725758

726-
// when tab view is changed, put the tabid as the current tab
759+
// When tab view is changed, put the tabId as the current tab
727760
chrome.tabs.onActivated.addListener((info) => {
728-
// get info about tab information from tabId
761+
// Get info about the tab information from tabId
729762
chrome.tabs.get(info.tabId, (tab) => {
730-
// never set a reactime instance to the active tab
763+
// Never set a reactime instance to the active tab
731764
if (!tab.pendingUrl?.match('^chrome-extension')) {
732765
activeTab = tab;
733766

734-
/**this setKeepAlive is here to make sure that the app does not stop working even
735-
* if chrome pauses to save energy.
736-
*/
737-
chrome.runtime.onStartup.addListener(() => {
738-
chrome.runtime.setKeepAlive(true);
739-
});
767+
// Send messages to active ports about the tab change
740768
if (portsArr.length > 0) {
741769
portsArr.forEach((bg) =>
742770
bg.postMessage({
@@ -757,8 +785,12 @@ chrome.runtime.onInstalled.addListener(() => {
757785
title: 'Reactime',
758786
contexts: ['page', 'selection', 'image', 'link'],
759787
});
788+
setupKeepAlive();
760789
});
761790

791+
chrome.runtime.onStartup.addListener(() => {
792+
setupKeepAlive();
793+
});
762794
// when context menu is clicked, listen for the menuItemId,
763795
// if user clicked on reactime, open the devtools window
764796

src/extension/contentScript.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { onTTFB, onLCP, onFID, onFCP, onCLS, onINP } from 'web-vitals';
44

55
function establishConnection() {
6-
const port = chrome.runtime.connect({ name: 'content-script' }); // Reconnect
6+
const port = chrome.runtime.connect({ name: 'keepAlivePort' }); // Reconnect if we lose connection to the port at any time
77
port.onMessage.addListener((msg) => {
88
console.log('Received message from background:', msg);
99
});

src/extension/overrideReducer.js

Lines changed: 0 additions & 173 deletions
Original file line numberDiff line numberDiff line change
@@ -1,176 +1,3 @@
1-
// (function () {
2-
// console.log('[Reactime Debug] Initial override script loaded');
3-
4-
// let attempts = 0;
5-
// const MAX_ATTEMPTS = 50;
6-
7-
// function verifyReactHooks() {
8-
// return (
9-
// window.React &&
10-
// typeof window.React.useReducer === 'function' &&
11-
// typeof window.React.useState === 'function'
12-
// );
13-
// }
14-
15-
// const checkReact = () => {
16-
// attempts++;
17-
// console.log(`[Reactime Debug] Checking for React (attempt ${attempts})`);
18-
19-
// // Only proceed if we can verify React hooks exist
20-
// if (verifyReactHooks()) {
21-
// console.log('[Reactime Debug] Found React with hooks via window.React');
22-
// setupOverride();
23-
// return;
24-
// }
25-
26-
// // Look for React devtools hook
27-
// if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
28-
// console.log('[Reactime Debug] Found React DevTools hook');
29-
30-
// // Watch for React registration
31-
// const originalInject = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject;
32-
// console.log('[Reactime Debug] Original inject method:', originalInject); //ellie
33-
34-
// window.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject = function (reactInstance) {
35-
// console.log(
36-
// '[Reactime Debug] React registered with DevTools, verifying hooks availability',
37-
// );
38-
39-
// // Give React a moment to fully initialize
40-
// setTimeout(() => {
41-
// if (verifyReactHooks()) {
42-
// console.log('[Reactime Debug] Hooks verified after DevTools registration');
43-
// setupOverride();
44-
// } else {
45-
// console.log(
46-
// '[Reactime Debug] Hooks not available after DevTools registration, continuing to check',
47-
// );
48-
// waitForHooks();
49-
// }
50-
// }, 2000);
51-
52-
// return originalInject.apply(this, arguments);
53-
// };
54-
55-
// return;
56-
// }
57-
58-
// waitForHooks();
59-
// };
60-
61-
// function waitForHooks() {
62-
// if (attempts < MAX_ATTEMPTS) {
63-
// const delay = Math.min(100 * attempts, 2000);
64-
// console.log(`[Reactime Debug] Hooks not found, retrying in ${delay}ms`);
65-
// setTimeout(checkReact, delay);
66-
// } else {
67-
// console.log('[Reactime Debug] Max attempts reached, React hooks not found');
68-
// }
69-
// }
70-
71-
// function setupOverride() {
72-
// try {
73-
// console.log('[Reactime Debug] Setting up useReducer override');
74-
75-
// if (!verifyReactHooks()) {
76-
// throw new Error('React hooks not available during override setup');
77-
// }
78-
79-
// const originalUseReducer = window.React.useReducer;
80-
// window.__REACTIME_REDUCER_MAP__ = new Map();
81-
82-
// window.React.useReducer = function (reducer, initialArg, init) {
83-
// console.log('[Reactime Debug] useReducer called with:', {
84-
// reducerName: reducer?.name || 'anonymous',
85-
// hasInitialArg: initialArg !== undefined,
86-
// hasInit: !!init,
87-
// });
88-
89-
// const actualInitialState = init ? init(initialArg) : initialArg;
90-
91-
// const wrappedReducer = (state, action) => {
92-
// try {
93-
// console.log('[Reactime Debug] Reducer called:', {
94-
// actionType: action?.type,
95-
// isTimeTravel: action?.type === '__REACTIME_TIME_TRAVEL__',
96-
// currentState: state,
97-
// action,
98-
// });
99-
100-
// if (action && action.type === '__REACTIME_TIME_TRAVEL__') {
101-
// return action.payload;
102-
// }
103-
// return reducer(state, action);
104-
// } catch (error) {
105-
// console.error('[Reactime Debug] Error in wrapped reducer:', error);
106-
// return state;
107-
// }
108-
// };
109-
110-
// const [state, dispatch] = originalUseReducer(wrappedReducer, actualInitialState);
111-
// const reducerId = Symbol('reactimeReducer');
112-
113-
// console.log('[Reactime Debug] New reducer instance created:', {
114-
// reducerId: reducerId.toString(),
115-
// initialState: actualInitialState,
116-
// currentState: state,
117-
// });
118-
119-
// window.__REACTIME_REDUCER_MAP__.set(reducerId, {
120-
// actionHistory: [],
121-
// dispatch,
122-
// initialState: actualInitialState,
123-
// currentState: state,
124-
// reducer: wrappedReducer,
125-
// });
126-
127-
// const wrappedDispatch = (action) => {
128-
// try {
129-
// console.log('[Reactime Debug] Dispatch called:', {
130-
// reducerId: reducerId.toString(),
131-
// action,
132-
// currentMapSize: window.__REACTIME_REDUCER_MAP__.size,
133-
// });
134-
135-
// const reducerInfo = window.__REACTIME_REDUCER_MAP__.get(reducerId);
136-
// reducerInfo.actionHistory.push(action);
137-
// reducerInfo.currentState = wrappedReducer(reducerInfo.currentState, action);
138-
// dispatch(action);
139-
// } catch (error) {
140-
// console.error('[Reactime Debug] Error in wrapped dispatch:', error);
141-
// dispatch(action);
142-
// }
143-
// };
144-
145-
// return [state, wrappedDispatch];
146-
// };
147-
148-
// console.log('[Reactime Debug] useReducer successfully overridden');
149-
// } catch (error) {
150-
// console.error('[Reactime Debug] Error during override setup:', error);
151-
// // If override fails, try again after a delay
152-
// setTimeout(checkReact, 500);
153-
// }
154-
// }
155-
156-
// // Start checking for React
157-
// checkReact();
158-
159-
// // Watch for dynamic React loading
160-
// const observer = new MutationObserver((mutations) => {
161-
// if (verifyReactHooks()) {
162-
// console.log('[Reactime Debug] React hooks found after DOM mutation');
163-
// observer.disconnect();
164-
// setupOverride();
165-
// }
166-
// });
167-
168-
// observer.observe(document, {
169-
// childList: true,
170-
// subtree: true,
171-
// });
172-
// })();
173-
1741
(function () {
1752
console.log('[Reactime Debug] Initial override script loaded');
1763

0 commit comments

Comments
 (0)