-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
552 lines (461 loc) · 18 KB
/
content.js
File metadata and controls
552 lines (461 loc) · 18 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Content script for Netacad Quiz Helper
console.log('Netacad Quiz Helper: Content script loaded in quiz iframe');
console.log('Current URL:', window.location.href);
// Function to search for elements in Shadow DOM
function findInShadowDOM(selector, root = document) {
// First try to find in the regular DOM
let elements = Array.from(root.querySelectorAll(selector));
// Then search in all shadow roots
const allElements = root.querySelectorAll('*');
allElements.forEach(el => {
if (el.shadowRoot) {
elements = elements.concat(findInShadowDOM(selector, el.shadowRoot));
}
});
return elements;
}
// Function to get text content from Shadow DOM element
function getTextFromShadowElement(element) {
if (!element) return '';
// Try regular textContent first
if (element.textContent && element.textContent.trim()) {
return element.textContent.trim();
}
// If element has shadow root, search inside it
if (element.shadowRoot) {
return element.shadowRoot.textContent?.trim() || '';
}
return '';
}
// Helper function to wait for an element to appear in shadow DOM
async function waitForElement(parentElement, selector, maxAttempts = 20) {
for (let i = 0; i < maxAttempts; i++) {
const element = parentElement.querySelector(selector);
if (element) {
return element;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
return null;
}
// Helper function to wait for shadow root content to load
async function waitForShadowContent(element, maxAttempts = 20) {
if (!element || !element.shadowRoot) return null;
for (let i = 0; i < maxAttempts; i++) {
if (element.shadowRoot.children.length > 0) {
return element.shadowRoot;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
return element.shadowRoot;
}
// Recursive function to find an element in shadow DOM tree
function findElementInShadowDOM(root, selector) {
// Try to find in current level
let element = root.querySelector(selector);
if (element) return element;
// Search in all shadow roots
const allElements = root.querySelectorAll('*');
for (let el of allElements) {
if (el.shadowRoot) {
element = findElementInShadowDOM(el.shadowRoot, selector);
if (element) return element;
}
}
return null;
}
// Function to extract question and options (based on iframe.js)
async function extractQuestionData() {
console.log('=== Starting Question Extraction ===');
try {
// Find ALL mcq-view elements and pick the visible/active one
console.log('🔍 Searching for active mcq-view...');
// Get all mcq-view elements recursively
let allMcqViews = [];
function findAllMcqViews(root) {
const mcqViews = root.querySelectorAll('mcq-view');
allMcqViews.push(...mcqViews);
const allElements = root.querySelectorAll('*');
for (let el of allElements) {
if (el.shadowRoot) {
findAllMcqViews(el.shadowRoot);
}
}
}
findAllMcqViews(document);
console.log(`Found ${allMcqViews.length} total mcq-view elements`);
if (allMcqViews.length === 0) {
console.log('❌ No mcq-view found in entire shadow DOM tree');
return null;
}
// Find the visible/active mcq-view
// The current question is typically the LAST visible one
let mcqViewElement = null;
let visibleMcqViews = [];
// Strategy 1: Find all visible mcq-views
for (let mcq of allMcqViews) {
const parent = mcq.closest('.block__container, [class*="block"]');
if (parent) {
const style = window.getComputedStyle(parent);
const isVisible = style.display !== 'none' &&
style.visibility !== 'hidden' &&
style.opacity !== '0';
// Also check if parent has 'animate' or 'active' class
const hasActiveClass = parent.classList.contains('animate') ||
parent.classList.contains('active') ||
parent.classList.contains('is-active');
console.log(`mcq-view check: visible=${isVisible}, hasActiveClass=${hasActiveClass}, classes=${parent.className}`);
if (isVisible) {
visibleMcqViews.push(mcq);
console.log(`Added to visible list (${visibleMcqViews.length} total visible)`);
}
}
}
// Strategy 2: Pick the LAST visible mcq-view (the current question)
if (visibleMcqViews.length > 0) {
mcqViewElement = visibleMcqViews[visibleMcqViews.length - 1];
console.log(`✅ Found active mcq-view (last visible, ${visibleMcqViews.length} visible total)`);
}
// Strategy 3: If no visible ones found, take the last one overall
if (!mcqViewElement && allMcqViews.length > 0) {
mcqViewElement = allMcqViews[allMcqViews.length - 1];
console.log('✅ Using last mcq-view element (fallback)');
}
if (!mcqViewElement) {
console.log('❌ Could not determine active mcq-view');
return null;
}
console.log('✅ Selected mcq-view element');
if (!mcqViewElement.shadowRoot) {
console.log('❌ mcq-view has no shadow root');
return null;
}
let mcqView = mcqViewElement.shadowRoot.querySelector("div");
if (!mcqView) {
console.log('❌ No div in mcq-view shadow root');
return null;
}
console.log('✅ Found mcq-view div');
// Now extract question and options (steps 16-17 from iframe.js)
// 16. Get question text
let headerContainer = mcqView.querySelector("div[class='component__header-container']");
if (!headerContainer) {
console.log('❌ No component__header-container found');
return null;
}
let baseView = headerContainer.querySelector("base-view");
if (!baseView || !baseView.shadowRoot) {
console.log('❌ No base-view or its shadow root found');
return null;
}
let bodyInner = baseView.shadowRoot.querySelector("div[class='component__body-inner mcq__body-inner']");
if (!bodyInner) {
console.log('❌ No component__body-inner found');
return null;
}
let questionText = bodyInner.textContent.trim();
console.log('📝 Extracted question:', questionText.substring(0, 150));
// Check if there's a code-with-mcq element (contains code snippet)
let codeText = '';
const codeWithMcq = mcqView.querySelector('code-with-mcq');
if (codeWithMcq && codeWithMcq.shadowRoot) {
const codeComponent = codeWithMcq.shadowRoot.querySelector("div[class='component']");
if (codeComponent) {
codeText = codeComponent.textContent.trim();
console.log('📝 Found code snippet:', codeText.substring(0, 150));
// Append code to question text
questionText = questionText + '\n\nCode:\n' + codeText;
console.log('📝 Question with code:', questionText);
}
}
else {
console.log('📝 No code-with-mcq element found, checking for sgpluse-codewindowwithmcq-view');
if (mcqView) {
const codeComponent = mcqView.querySelector("sgpluse-codewindowwithmcq-view")
if (codeComponent && codeComponent.shadowRoot) {
const codeShadowRoot = codeComponent.shadowRoot
const codePre = codeShadowRoot.querySelector("pre")
const codeCode = codePre.querySelector('code')
console.log('📝 Found code component:', codeCode);
if (codeCode) {
let codeWebComponent = codeCode.querySelector('code-window-webcomponent-mcq');
if (codeWebComponent && codeWebComponent.shadowRoot) {
codeText = codeWebComponent.shadowRoot.querySelector('div[class="code-container"]').textContent.trim();
}
console.log('📝 Found code snippet:', codeText);
// Append code to question text
questionText = questionText + '\n\nCode:\n' + codeText;
console.log('📝 Question with code:', questionText);
}
}
else {
console.log('❌ No sgpluse-codewindowwithmcq-view element found');
}
}
}
// 17. Get options
let optionNodes = mcqView.querySelectorAll('.mcq__item-text-inner');
if (optionNodes.length === 0) {
console.log('❌ No option nodes found');
return null;
}
console.log(`✅ Found ${optionNodes.length} options`);
let options = Array.from(optionNodes).map((node, index) => {
const text = node.textContent.trim();
console.log(`Option ${index}: ${text.substring(0, 50)}`);
return {
index: index,
text: text,
element: node.closest('.mcq__item')
};
});
console.log('=== Extraction Complete ===\n');
return {
question: questionText,
options: options
};
} catch (error) {
console.error('❌ Error during extraction:', error);
return null;
}
}
// Function to highlight the correct answer
function highlightCorrectAnswer(correctOptionIndex) {
console.log('=== Starting Highlight ===');
console.log('Highlighting option index:', correctOptionIndex);
try {
// Find ALL mcq-view elements and pick the visible/active one (same as extraction)
let allMcqViews = [];
function findAllMcqViews(root) {
const mcqViews = root.querySelectorAll('mcq-view');
allMcqViews.push(...mcqViews);
const allElements = root.querySelectorAll('*');
for (let el of allElements) {
if (el.shadowRoot) {
findAllMcqViews(el.shadowRoot);
}
}
}
findAllMcqViews(document);
console.log(`Found ${allMcqViews.length} total mcq-view elements for highlighting`);
if (allMcqViews.length === 0) {
console.log('❌ No mcq-view found for highlighting');
return;
}
// Find the visible/active mcq-view (same logic as extraction)
let mcqViewElement = null;
let visibleMcqViews = [];
for (let mcq of allMcqViews) {
const parent = mcq.closest('.block__container, [class*="block"]');
if (parent) {
const style = window.getComputedStyle(parent);
const isVisible = style.display !== 'none' &&
style.visibility !== 'hidden' &&
style.opacity !== '0';
if (isVisible) {
visibleMcqViews.push(mcq);
}
}
}
// Pick the LAST visible mcq-view (the current question)
if (visibleMcqViews.length > 0) {
mcqViewElement = visibleMcqViews[visibleMcqViews.length - 1];
console.log(`✅ Found active mcq-view for highlighting (last visible, ${visibleMcqViews.length} visible total)`);
}
// Fallback: use the last one overall
if (!mcqViewElement && allMcqViews.length > 0) {
mcqViewElement = allMcqViews[allMcqViews.length - 1];
console.log('✅ Using last mcq-view for highlighting (fallback)');
}
if (!mcqViewElement) {
console.log('❌ Could not determine active mcq-view for highlighting');
return;
}
console.log('✅ Selected mcq-view for highlighting');
if (!mcqViewElement.shadowRoot) {
console.log('❌ mcq-view has no shadow root');
return;
}
let mcqView = mcqViewElement.shadowRoot.querySelector("div");
if (!mcqView) {
console.log('❌ No div in mcq-view shadow root');
return;
}
// Get all option elements
const optionElements = mcqView.querySelectorAll('.mcq__item');
console.log(`Found ${optionElements.length} option elements for highlighting`);
// Remove any existing highlights
optionElements.forEach(element => {
element.classList.remove('ai-correct-answer');
element.style.removeProperty('background-color');
element.style.removeProperty('border');
element.style.removeProperty('box-shadow');
element.style.removeProperty('color');
// Reset text color for all text elements inside
const textElements = element.querySelectorAll('*');
textElements.forEach(el => {
el.style.removeProperty('color');
});
});
// Highlight the correct answer
if (correctOptionIndex >= 0 && correctOptionIndex < optionElements.length) {
const correctElement = optionElements[correctOptionIndex];
correctElement.classList.add('ai-correct-answer');
// Apply inline styles - green background with white text
correctElement.style.backgroundColor = '#22c55e';
correctElement.style.border = '3px solid #16a34a';
correctElement.style.borderRadius = '8px';
correctElement.style.boxShadow = '0 0 0 4px rgba(34, 197, 94, 0.2)';
correctElement.style.color = 'white';
// Make sure all text inside is white
const textElements = correctElement.querySelectorAll('*');
textElements.forEach(el => {
el.style.color = 'white';
});
console.log(`✅ Highlighted option ${correctOptionIndex} as correct`);
} else {
console.log(`❌ Invalid option index: ${correctOptionIndex} (total options: ${optionElements.length})`);
}
console.log('=== Highlight Complete ===\n');
} catch (error) {
console.error('❌ Error during highlighting:', error);
}
}
// Function to create the helper buttons (simple and advanced)
function createHelperButton(targetDocument = document) {
// Check if buttons already exist
if (document.getElementById('netacad-ai-helper-btn-simple')) {
console.log('Buttons already exist in main document');
return;
}
if (targetDocument !== document && targetDocument.getElementById('netacad-ai-helper-btn-simple')) {
console.log('Buttons already exist in iframe');
return;
}
// Create Simple Button (Green)
const simpleButton = targetDocument.createElement('button');
simpleButton.id = 'netacad-ai-helper-btn-simple';
simpleButton.innerHTML = '🤖 Get AI Answer';
simpleButton.className = 'ai-helper-button ai-helper-button-simple';
// Create Advanced Button (Red)
const advancedButton = targetDocument.createElement('button');
advancedButton.id = 'netacad-ai-helper-btn-advanced';
advancedButton.innerHTML = '🔥 Advanced AI (Code/Math)';
advancedButton.className = 'ai-helper-button ai-helper-button-advanced';
// Simple button click handler
simpleButton.addEventListener('click', async () => {
await handleButtonClick(simpleButton, 'simple', '🤖 Get AI Answer');
});
// Advanced button click handler
advancedButton.addEventListener('click', async () => {
await handleButtonClick(advancedButton, 'coding', '🔥 Advanced AI (Code/Math)');
});
// Add buttons to the target document body
targetDocument.body.appendChild(simpleButton);
targetDocument.body.appendChild(advancedButton);
console.log('AI helper buttons added to', targetDocument === document ? 'main page' : 'iframe');
}
// Shared button click handler
async function handleButtonClick(button, modelType, originalText) {
button.disabled = true;
button.innerHTML = '⏳ Analyzing...';
const questionData = await extractQuestionData();
if (!questionData) {
alert('Could not extract question data. Make sure you are on a quiz page.');
button.disabled = false;
button.innerHTML = originalText;
return;
}
try {
// Send message to background script with model type
const response = await chrome.runtime.sendMessage({
action: 'getAnswer',
question: questionData.question,
options: questionData.options.map(opt => opt.text),
modelType: modelType
});
console.log('AI Response received:', response);
if (response.success) {
highlightCorrectAnswer(response.answerIndex);
button.innerHTML = '✅ Answer Highlighted';
setTimeout(() => {
button.innerHTML = originalText;
button.disabled = false;
}, 2000);
} else {
console.error('AI Error Details:', response.error);
alert('AI Error: ' + response.error);
button.disabled = false;
button.innerHTML = originalText;
}
} catch (error) {
console.error('Error getting AI answer:', error);
alert('Error communicating with AI. Please check your API key in the extension popup.');
button.disabled = false;
button.innerHTML = originalText;
}
}
// Function to check if quiz exists and create buttons
function checkForQuiz() {
console.log('Checking for quiz in current document...');
console.log('Current URL:', window.location.href);
// Check if app-root exists (indicates we're in the quiz iframe)
const appRoot = document.querySelector('app-root');
console.log('app-root element:', appRoot);
const buttonsExist = document.getElementById('netacad-ai-helper-btn-simple');
console.log('Buttons exist:', buttonsExist);
if (appRoot && !buttonsExist) {
console.log('Quiz iframe detected, creating buttons');
createHelperButton(document);
} else if (!appRoot) {
console.log('No app-root element found in this document');
}
}
// Wait for page to load with multiple attempts
let checkAttempts = 0;
const maxAttempts = 20;
function tryCheckForQuiz() {
checkAttempts++;
console.log(`Attempt ${checkAttempts} to find quiz`);
checkForQuiz();
if (checkAttempts < maxAttempts && !document.getElementById('netacad-ai-helper-btn-simple')) {
setTimeout(tryCheckForQuiz, 500);
}
}
// Initialize when page is fully loaded
function initialize() {
console.log('Initializing extension in quiz iframe...');
// Start checking for quiz
setTimeout(tryCheckForQuiz, 1000);
// Also observe for dynamic content changes (for SPA navigation)
const observer = new MutationObserver((mutations) => {
// Only check if buttons don't exist
if (!document.getElementById('netacad-ai-helper-btn-simple')) {
const appRoot = document.querySelector('app-root');
if (appRoot) {
console.log('app-root detected via mutation observer');
checkForQuiz();
}
}
});
if (document.body) {
observer.observe(document.body, {
childList: true,
subtree: true
});
}
}
// Wait for complete page load (including iframes)
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM Content Loaded');
// Wait a bit more for iframe to be ready
setTimeout(initialize, 500);
});
} else if (document.readyState === 'interactive') {
console.log('Document interactive');
setTimeout(initialize, 500);
} else {
console.log('Document already complete');
initialize();
}