-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_script.js
More file actions
250 lines (198 loc) Β· 7.83 KB
/
content_script.js
File metadata and controls
250 lines (198 loc) Β· 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
const currentUrl = `${location.origin}${location.pathname}`;
console.log("π Content script loaded for URL:", currentUrl);
/**
* Get all unique radio button names on the page
* @returns {string[]} Array of radio button names
*/
function getRadioButtonNames() {
const radioButtons = document.querySelectorAll("input[type=radio]");
const names = [...radioButtons].map(radio => radio.name);
const uniqueNames = [...new Set(names)];
console.log("π Found radio buttons:", radioButtons.length);
console.log("π Unique radio button names:", uniqueNames);
return uniqueNames;
}
/**
* Check radio buttons based on stored configuration
* @param {string[]} names - Array of radio button names
* @param {string} url - Current page URL
*/
async function checkStoredRadioButtons(names, url) {
console.log("π Checking stored radio buttons...");
try {
const { pairs } = await chrome.storage.sync.get("pairs");
console.log("π Retrieved pairs from storage:", pairs);
if (!pairs || pairs.length === 0) {
console.log("βΉοΈ No stored pairs found");
return;
}
let foundMatch = false;
pairs.forEach(({ url: storedUrl, checks }) => {
console.log(`π Checking if '${url}' includes '${storedUrl}'`);
if (url.includes(storedUrl)) {
console.log("β
URL match found! Applying stored selections...");
console.log("π Stored checks:", checks);
applyCheckedState(names, checks);
foundMatch = true;
}
});
if (!foundMatch) {
console.log("β No matching URL found in stored pairs");
}
} catch (error) {
console.error("π₯ Error checking stored radio buttons:", error);
}
}
/**
* Save current radio button state to storage
* @param {string[]} names - Array of radio button names
* @param {string} url - Current page URL
*/
async function saveRadioButtonState(names, url) {
console.log("πΎ Saving radio button state for URL:", url);
console.log("π Radio button names:", names);
try {
const { pairs = [] } = await chrome.storage.sync.get("pairs");
console.log("π Current pairs in storage:", pairs);
const checkedIndices = findCheckedIndices(names);
console.log("π― Found checked indices:", checkedIndices);
if (checkedIndices.length === 0) {
console.warn("β οΈ No radio buttons are currently selected");
}
// Check if URL already exists and update, otherwise add new entry
const existingIndex = pairs.findIndex(pair => pair.url.includes(url));
if (existingIndex !== -1) {
console.log("π Updating existing entry at index:", existingIndex);
// Update existing entry
pairs[existingIndex] = {
url: url,
checks: checkedIndices
};
} else {
console.log("β Adding new entry");
// Add new entry
pairs.push({
url: url,
checks: checkedIndices
});
}
await chrome.storage.sync.set({ pairs });
console.log("β
Radio button state saved successfully");
console.log("π Final pairs:", pairs);
} catch (error) {
console.error("π₯ Error saving radio button state:", error);
}
}
/**
* Find indices of checked radio buttons for each name group
* @param {string[]} names - Array of radio button names
* @returns {number[]} Array of checked indices
*/
function findCheckedIndices(names) {
console.log("π Finding checked indices for names:", names);
const checkedIndices = [];
for (let i = 0; i < names.length; i++) {
const buttons = document.getElementsByName(names[i]);
console.log(`π Checking group '${names[i]}' with ${buttons.length} buttons`);
let foundChecked = false;
for (let j = 0; j < buttons.length; j++) {
if (buttons[j].checked) {
console.log(`β
Found checked button at index ${j} for group '${names[i]}'`);
checkedIndices.push(j);
foundChecked = true;
break; // Only one radio button per name group can be checked
}
}
if (!foundChecked) {
console.log(`β No checked button found for group '${names[i]}'`);
checkedIndices.push(-1); // -1 indicates no selection
}
}
console.log("π Final checked indices:", checkedIndices);
return checkedIndices;
}
/**
* Apply checked state to radio buttons
* @param {string[]} names - Array of radio button names
* @param {number[]} checkedIndices - Array of indices to check
*/
function applyCheckedState(names, checkedIndices) {
console.log("π― Applying checked state...");
console.log("π Names:", names);
console.log("π Checked indices:", checkedIndices);
if (!checkedIndices || checkedIndices.length !== names.length) {
console.warn("β οΈ Checked indices don't match radio button names");
console.log(`Expected ${names.length} indices, got ${checkedIndices ? checkedIndices.length : 0}`);
return;
}
let appliedCount = 0;
for (let i = 0; i < names.length; i++) {
const buttons = document.getElementsByName(names[i]);
const indexToCheck = checkedIndices[i];
console.log(`π Processing group '${names[i]}' (${buttons.length} buttons)`);
console.log(`π― Index to check: ${indexToCheck}`);
if (indexToCheck >= 0 && buttons[indexToCheck]) {
buttons[indexToCheck].checked = true;
console.log(`β
Checked button at index ${indexToCheck} for group '${names[i]}'`);
appliedCount++;
} else if (indexToCheck === -1) {
console.log(`βΉοΈ No selection for group '${names[i]}'`);
} else {
console.warn(`β οΈ Invalid index ${indexToCheck} for group '${names[i]}' (max: ${buttons.length - 1})`);
}
}
console.log(`β
Applied ${appliedCount} radio button selections`);
}
// Message listener for popup communication
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("π¨ Message received from popup:", request);
if (request.greeting === "save") {
console.log("πΎ Processing save request from popup");
(async () => {
try {
const names = getRadioButtonNames();
if (names.length === 0) {
console.warn("β οΈ No radio buttons found on this page");
sendResponse({ error: "No radio buttons found on this page" });
return;
}
await saveRadioButtonState(names, currentUrl);
console.log("β
Save request completed successfully");
sendResponse({ farewell: "save done" });
} catch (error) {
console.error("π₯ Error processing save request:", error);
sendResponse({ error: error.message });
}
})();
return true; // Keep message channel open for async response
}
console.log("β Unknown message greeting:", request.greeting);
sendResponse({ error: "Unknown message type" });
});
// Initialize auto-checking functionality
(async () => {
console.log("π Initializing auto-checking functionality...");
try {
const names = getRadioButtonNames();
if (names.length === 0) {
console.log("βΉοΈ No radio buttons found on this page");
return;
}
// Check stored radio buttons with a delay to ensure page is fully loaded
const checkWithDelay = async () => {
await checkStoredRadioButtons(names, currentUrl);
};
// Check multiple times with intervals to handle dynamic content
console.log("β° Starting periodic checks...");
const timer = setInterval(checkWithDelay, 100);
setTimeout(() => {
clearInterval(timer);
console.log("β° Periodic checks completed");
}, 2000);
console.log("π― [AUTO RADIO BUTTON CHECKER is activated]");
console.log("π Found radio buttons in this page:", names);
console.log("π Current URL:", currentUrl);
} catch (error) {
console.error("π₯ Error during initialization:", error);
}
})();