Skip to content

Commit 36a5b8e

Browse files
committed
split into 2 files
1 parent f1a074b commit 36a5b8e

File tree

2 files changed

+117
-110
lines changed

2 files changed

+117
-110
lines changed

button-injection.js

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
'use strict';
2+
// button-injection.js version 1.0
3+
/**
4+
* Button Injection Logic for the ChatGPT Chrome extension.
5+
* This file contains functions to handle custom button injection into the webpage,
6+
* including resiliency checks and re-initialization measures.
7+
*/
8+
//Instructions for AI: do not remove comments! MUST NOT REMOVE COMMENTS. This one too!
9+
// ALL CODE IN ALL FILES MUST USE logConCgp FOR LOGGING. NO CONSOLE LOGGING.
10+
11+
12+
/**
13+
* Checks whether the custom buttons modifications already exist in the DOM.
14+
* @returns {boolean} - True if modifications exist, false otherwise.
15+
*/
16+
function doCustomModificationsExist() {
17+
return document.getElementById(window.InjectionTargetsOnWebsite.selectors.buttonsContainerId) !== null;
18+
}
19+
20+
/**
21+
* Inserts custom buttons, separators and settings toggles into the webpage and starts resiliency checks if enabled.
22+
* @param {boolean} enableResiliency - Flag to enable or disable resiliency checks.
23+
* @param {string} activeWebsite - The identifier of the active website.
24+
*/
25+
function buttonBoxCheckingAndInjection(enableResiliency = true, activeWebsite) {
26+
logConCgp('[button-injection] Checking if mods already exist...');
27+
if (doCustomModificationsExist() && !enableResiliency) {
28+
logConCgp('[button-injection] Modifications already exist and resiliency is disabled. Skipping initialization.');
29+
return;
30+
}
31+
32+
// Load the saved states of toggle switches
33+
MaxExtensionInterface.loadToggleStates();
34+
logConCgp('[button-injection] Toggle states have been loaded.');
35+
36+
// Initialize the shared flag
37+
let targetFound = false;
38+
39+
// Define the selector to wait for using InjectionTargetsOnWebsite
40+
const selectors = window.InjectionTargetsOnWebsite.selectors.containers;
41+
// A unified callback function will search for div where we will insert stuff
42+
const handleTargetDiv = (targetDiv) => {
43+
if (!targetFound) {
44+
targetFound = true; // Set the flag to prevent other callbacks from executing
45+
logConCgp('[button-injection] Target div has been found:', targetDiv);
46+
// Insert custom elements into the target container on the webpage
47+
window.MaxExtensionButtonsInit.createAndInsertCustomElements(targetDiv);
48+
49+
// Initiate resiliency checks only after the first successful modification
50+
if (!window.globalMaxExtensionConfig.firstModificationCompleted && enableResiliency) {
51+
window.globalMaxExtensionConfig.firstModificationCompleted = true;
52+
logConCgp('[button-injection] First modification complete. Starting resiliency checks.');
53+
commenceEnhancedResiliencyChecks();
54+
}
55+
}
56+
};
57+
58+
// Wait for the target element to appear in the DOM and then handle it
59+
MaxExtensionUtils.waitForElements(selectors, handleTargetDiv);
60+
}
61+
62+
/**
63+
* Initiates enhanced resiliency checks to ensure the extension remains functional on the webpage.
64+
*/
65+
function commenceEnhancedResiliencyChecks() {
66+
let consecutiveClearCheckCount = 0;
67+
const requiredConsecutiveClearChecks = 2; // missing for this many times = reinsert
68+
const maximumTotalIterations = 16;
69+
let totalIterationsPerformed = 0;
70+
const intervalTimeInMilliseconds = 50;
71+
72+
logConCgp('[button-injection] Beginning enhanced resiliency checks...');
73+
logConCgp(`[button-injection] Requires ${requiredConsecutiveClearChecks} consecutive clear checks.`);
74+
75+
const resiliencyCheckInterval = setInterval(() => {
76+
totalIterationsPerformed++;
77+
78+
if (doCustomModificationsExist()) {
79+
consecutiveClearCheckCount = 0; // Reset counter if modifications are detected
80+
logConCgp(`[button-injection] Existing modifications detected. Resetting consecutive clear check counter. (Iteration ${totalIterationsPerformed}/${maximumTotalIterations})`);
81+
} else {
82+
consecutiveClearCheckCount++;
83+
logConCgp(`[button-injection] No modifications detected. Consecutive clear checks: ${consecutiveClearCheckCount}/${requiredConsecutiveClearChecks}`);
84+
}
85+
86+
// Verify if the required number of consecutive clear checks has been met
87+
if (consecutiveClearCheckCount >= requiredConsecutiveClearChecks) {
88+
logConCgp('[button-injection] Required consecutive clear checks achieved. Proceeding with initialization.');
89+
clearInterval(resiliencyCheckInterval);
90+
enforceResiliencyMeasures();
91+
}
92+
93+
// Safety measure to prevent infinite loops
94+
if (totalIterationsPerformed >= maximumTotalIterations) {
95+
logConCgp('[button-injection] Maximum iterations reached without achieving consecutive clear checks.');
96+
clearInterval(resiliencyCheckInterval);
97+
98+
// Only proceed if no modifications are present at this point
99+
if (!doCustomModificationsExist()) {
100+
logConCgp('[button-injection] No modifications present after maximum iterations. Proceeding cautiously.');
101+
enforceResiliencyMeasures();
102+
} else {
103+
logConCgp('[button-injection] Modifications still present after maximum iterations. Aborting initialization.');
104+
}
105+
}
106+
}, intervalTimeInMilliseconds);
107+
}
108+
109+
/**
110+
* Enforces resiliency by re-initializing the extension without further resiliency checks.
111+
* Inserts custom elements into the webpage to restore functionality.
112+
*/
113+
function enforceResiliencyMeasures() {
114+
logConCgp('[button-injection] Enforcing resiliency measures. Re-initializing without resiliency checks.');
115+
buttonBoxCheckingAndInjection(false);
116+
}

init.js

Lines changed: 1 addition & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,6 @@ function commenceExtensionInitialization(configurationObject) {
5959

6060
logConCgp('[init] Configuration has been received:', configurationObject);
6161

62-
/**
63-
* Checks whether the custom buttons modifications already exist in the DOM.
64-
* @returns {boolean} - True if modifications exist, false otherwise.
65-
* @description Helper function that checks if the custom buttons container exists in the DOM to prevent duplication.
66-
*/
67-
function doCustomModificationsExist() {
68-
return document.getElementById(window.InjectionTargetsOnWebsite.selectors.buttonsContainerId) !== null;
69-
}
70-
7162
/**
7263
* Selects the correct initialization path based on the active website and sets up keyboard shortcuts if enabled.
7364
* Injects custom elements into the webpage accordingly.
@@ -78,7 +69,7 @@ function commenceExtensionInitialization(configurationObject) {
7869
const activeWebsite = window.InjectionTargetsOnWebsite.activeSite;
7970
logConCgp('[init] Active website detected:', activeWebsite);
8071

81-
// Initialize based on the active website
72+
// Initialize button injection logic (moved to separate file "button-injection.js")
8273
buttonBoxCheckingAndInjection(true, activeWebsite);
8374

8475
// Enable keyboard shortcuts if configured and on ChatGPT
@@ -124,106 +115,6 @@ function commenceExtensionInitialization(configurationObject) {
124115
}
125116
}
126117

127-
/**
128-
* Inserts custom buttons, separators and settings toggles into the webpage and starts resiliency checks if enabled.
129-
* @param {boolean} enableResiliency - Flag to enable or disable resiliency checks.
130-
*/
131-
function buttonBoxCheckingAndInjection(enableResiliency = true, activeWebsite) {
132-
logConCgp('[init] Checking if mods already exist...');
133-
if (doCustomModificationsExist() && !enableResiliency) {
134-
logConCgp('[init] Modifications already exist and resiliency is disabled. Skipping initialization.');
135-
return;
136-
}
137-
138-
// Load the saved states of toggle switches
139-
MaxExtensionInterface.loadToggleStates();
140-
logConCgp('[init] Toggle states have been loaded.');
141-
142-
// Initialize the shared flag
143-
let targetFound = false;
144-
145-
// Define the selector to wait for using InjectionTargetsOnWebsite
146-
const selectors = window.InjectionTargetsOnWebsite.selectors.containers;
147-
// A unified callback function will search for div where we will insert stuff and
148-
const handleTargetDiv = (targetDiv) => {
149-
if (!targetFound) {
150-
targetFound = true; // Set the flag to prevent other callbacks from executing
151-
logConCgp('[init] Target div has been found:', targetDiv);
152-
// Insert custom elements into the target container on the webpage
153-
window.MaxExtensionButtonsInit.createAndInsertCustomElements(targetDiv);
154-
155-
// Initiate resiliency checks only after the first successful modification
156-
if (!globalMaxExtensionConfig.firstModificationCompleted && enableResiliency) {
157-
globalMaxExtensionConfig.firstModificationCompleted = true;
158-
logConCgp('[init] First modification complete. Starting resiliency checks.');
159-
commenceEnhancedResiliencyChecks();
160-
}
161-
}
162-
};
163-
164-
// Wait for the target element to appear in the DOM and then handle it
165-
MaxExtensionUtils.waitForElements(selectors, handleTargetDiv);
166-
}
167-
168-
/**
169-
* Initiates enhanced resiliency checks to ensure the extension remains functional on the webpage.
170-
* Periodically checks if custom modifications exist and re-initializes if necessary.
171-
*/
172-
function commenceEnhancedResiliencyChecks() {
173-
let consecutiveClearCheckCount = 0;
174-
// This looks if the buttons present for few times, and tries to insert them again.
175-
const requiredConsecutiveClearChecks = 2; // missing for this many times = reinsert
176-
const maximumTotalIterations = 16;
177-
let totalIterationsPerformed = 0;
178-
const intervalTimeInMilliseconds = 50;
179-
180-
logConCgp('[init] Beginning enhanced resiliency checks...');
181-
logConCgp(`[init] Requires ${requiredConsecutiveClearChecks} consecutive clear checks.`);
182-
183-
184-
const resiliencyCheckInterval = setInterval(() => {
185-
totalIterationsPerformed++;
186-
187-
if (doCustomModificationsExist()) {
188-
consecutiveClearCheckCount = 0; // Reset counter if modifications are detected
189-
logConCgp(`[init] Existing modifications detected. Resetting consecutive clear check counter. (Iteration ${totalIterationsPerformed}/${maximumTotalIterations})`);
190-
} else {
191-
consecutiveClearCheckCount++;
192-
logConCgp(`[init] No modifications detected. Consecutive clear checks: ${consecutiveClearCheckCount}/${requiredConsecutiveClearChecks}`);
193-
}
194-
195-
// Verify if the required number of consecutive clear checks has been met
196-
if (consecutiveClearCheckCount >= requiredConsecutiveClearChecks) {
197-
logConCgp('[init] Required consecutive clear checks achieved. Proceeding with initialization.');
198-
clearInterval(resiliencyCheckInterval);
199-
enforceResiliencyMeasures();
200-
}
201-
202-
// Safety measure to prevent infinite loops
203-
if (totalIterationsPerformed >= maximumTotalIterations) {
204-
logConCgp('[init] Maximum iterations reached without achieving consecutive clear checks.');
205-
clearInterval(resiliencyCheckInterval);
206-
207-
// Only proceed if no modifications are present at this point
208-
if (!doCustomModificationsExist()) {
209-
logConCgp('[init] No modifications present after maximum iterations. Proceeding cautiously.');
210-
enforceResiliencyMeasures();
211-
} else {
212-
logConCgp('[init] Modifications still present after maximum iterations. Aborting initialization.');
213-
}
214-
}
215-
}, intervalTimeInMilliseconds);
216-
}
217-
218-
/**
219-
* Enforces resiliency by re-initializing the extension without further resiliency checks.
220-
* Inserts custom elements into the webpage to restore functionality.
221-
*/
222-
function enforceResiliencyMeasures() {
223-
logConCgp('[init] Enforcing resiliency measures. Re-initializing without resiliency checks.');
224-
buttonBoxCheckingAndInjection(false);
225-
}
226-
227118
/**
228119
* Debounces a function to limit how often it can be executed.
229120
* @param {Function} func - The function to debounce.

0 commit comments

Comments
 (0)