-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
2519 lines (2340 loc) · 103 KB
/
content.js
File metadata and controls
2519 lines (2340 loc) · 103 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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Content script for extracting text from web pages
(function() {
'use strict';
// Increment this when content script behavior changes
const CONTENT_SCRIPT_VERSION = '3';
/**
* Check if an element is visible
*/
function isElementVisible(element) {
if (!element) return false;
const style = window.getComputedStyle(element);
return style.display !== 'none' &&
style.visibility !== 'hidden' &&
style.opacity !== '0' &&
element.offsetHeight > 0 &&
element.offsetWidth > 0;
}
/**
* Check if element is likely an ad or unwanted content
*/
function isUnwantedElement(element) {
const unwantedSelectors = [
'script', 'style', 'noscript', 'iframe', 'object', 'embed',
'[class*="ad"]', '[id*="ad"]', '[class*="ads"]', '[id*="ads"]',
'[class*="advertisement"]', '[class*="sponsor"]', '[class*="promo"]',
'.sidebar', '.footer', '.header', '.nav', '.navigation', '.menu'
];
for (const selector of unwantedSelectors) {
if (element.matches && element.matches(selector)) {
return true;
}
}
const className = element.className || '';
const id = element.id || '';
const unwantedKeywords = ['ad', 'ads', 'advertisement', 'sponsor', 'promo', 'banner'];
return unwantedKeywords.some(keyword =>
className.toLowerCase().includes(keyword) ||
id.toLowerCase().includes(keyword)
);
}
/**
* Clean and normalize text
*/
function cleanText(text) {
// Preserve newlines to keep rows/labels separate; trim spaces within lines
const normalized = text
.replace(/\r\n?/g, '\n')
.split('\n')
.map(line => line.replace(/\s+/g, ' ').trim())
.filter(line => line.length > 0)
.join('\n');
return normalized;
}
function shouldIncludeElement(el, includeHidden) {
if (!el) return false;
if (isUnwantedElement(el)) return false;
return includeHidden || isElementVisible(el);
}
// Scroll through the page to trigger lazy-loaded content
async function preloadLazyContent() {
try {
const total = Math.max(document.body?.scrollHeight || 0, document.documentElement?.scrollHeight || 0, window.innerHeight * 2);
const step = Math.max(300, Math.floor(window.innerHeight * 0.9));
for (let y = 0; y < total; y += step) {
window.scrollTo(0, y);
await new Promise(r => setTimeout(r, 80));
}
window.scrollTo(0, 0);
await new Promise(r => setTimeout(r, 80));
} catch (_) {
// ignore
}
}
function selectMainContainer() {
const candidates = [
document.querySelector('main'),
document.getElementById('content'),
document.querySelector('.content'),
document.querySelector('#main'),
document.querySelector('article')
].filter(Boolean);
return candidates[0] || document.body;
}
// Heuristic boilerplate detector (headers, footers, navs, breadcrumbs, sidebars)
function isBoilerplateElement(el) {
try {
const sels = [
'header','footer','nav','aside',
'[role="navigation"]','[aria-label*="breadcrumb" i]',
'.breadcrumb','.breadcrumbs','.menu','.navbar',
'.sidebar','.site-header','.site-footer','.topbar'
];
return sels.some(s => el.closest && el.closest(s));
} catch (_) { return false; }
}
// Positional header/footer filter
function isInHeaderFooterZone(el) {
try {
if (!el || !el.getBoundingClientRect) return false;
const rect = el.getBoundingClientRect();
const vh = Math.max(window.innerHeight || 0, document.documentElement.clientHeight || 0);
const nearTop = rect.top < 140;
const nearBottom = rect.bottom > (vh - 180);
const inHeader = el.closest && (el.closest('header,[role="banner"],nav') != null);
const inFooter = el.closest && (el.closest('footer,[role="contentinfo"]') != null);
return (nearTop && inHeader) || (nearBottom && inFooter) || inHeader || inFooter;
} catch (_) { return false; }
}
// Find the main content container to reduce header/footer/menu noise
function findMainContentContainer() {
try {
const prefer = [
'main','[role="main"]','article','#content','.content',
'#primary','.main','.main-content','.content-area','.site-content'
];
const direct = prefer.map(sel => document.querySelector(sel)).filter(Boolean);
const pool = direct.length
? direct
: Array.from(document.querySelectorAll('main, article, #content, .content, #primary, .site-content, .container'));
let best = selectMainContainer();
let bestScore = 0;
for (const el of pool) {
if (!el) continue;
const textLen = ((el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim()).length;
const penalty = (el.querySelectorAll('nav, header, footer, .sidebar, [role="navigation"], .menu, .breadcrumbs, .breadcrumb').length || 0) * 200;
const score = textLen - penalty;
if (score > bestScore) { bestScore = score; best = el; }
}
return best || selectMainContainer();
} catch (_) { return selectMainContainer(); }
}
// Extract text within a specific root to avoid global boilerplate
function extractDomOrderedTextWithin(root, includeHidden = false) {
try {
const selector = [
'h1','h2','h3','h4','h5','h6',
'p','li','table','blockquote','dt','dd','figcaption'
].join(',');
const nodes = Array.from((root || document).querySelectorAll(selector));
const lines = [];
let last = '';
nodes.forEach(node => {
if (isBoilerplateElement(node)) return;
if (!shouldIncludeElement(node, includeHidden)) return;
if (isInHeaderFooterZone(node)) return;
if (node.tagName === 'TABLE') {
const tblRows = [];
const trs = node.querySelectorAll('tr');
trs.forEach(tr => {
const cells = Array.from(tr.querySelectorAll('th,td'))
.map(c => cleanText(c.textContent).replace(/\s*:\s*$/,'').replace(/^[:\-\s]+/,''))
.filter(Boolean);
if (cells.length === 2) {
tblRows.push(`${cells[0]}: ${cells[1]}`);
} else if (cells.length > 0) {
tblRows.push(cells.join(' | '));
}
});
if (tblRows.length) {
tblRows.forEach(row => {
if (row && row !== last) {
lines.push(row);
last = row;
}
});
}
return;
}
let text = cleanText(node.textContent || '');
if (!text) return;
if (node.tagName === 'LI') {
text = `• ${text}`;
}
if (text && text !== last) {
lines.push(text);
last = text;
}
});
return lines.join('\n');
} catch (_) {
return '';
}
}
function getContainerSignature(el) {
try {
const txt = (el?.innerText || el?.textContent || '').replace(/\s+/g, ' ').trim();
return `${txt.length}:${txt.slice(0, 200)}`;
} catch (_) { return `${Date.now()}`; }
}
async function waitForContentMutation(el, prevSig, timeoutMs = 2500) {
return new Promise(resolve => {
let done = false;
const check = () => {
if (done) return;
const nowSig = getContainerSignature(el);
if (nowSig !== prevSig) {
done = true;
obs.disconnect();
resolve(true);
}
};
const obs = new MutationObserver(() => setTimeout(check, 30));
obs.observe(el, { subtree: true, childList: true, characterData: true });
const id = setTimeout(() => { if (!done) { done = true; obs.disconnect(); resolve(false); } }, timeoutMs);
// immediate first check
setTimeout(check, 50);
});
}
function getPaginationElements() {
const containers = Array.from(document.querySelectorAll('.pagination, nav[aria-label*="pagination" i], .page-numbers, .pager'));
const inContainers = containers.flatMap(c => Array.from(c.querySelectorAll('a,button')));
const candidates = inContainers.length ? inContainers : Array.from(document.querySelectorAll('a.page-link, .pagination a, .page-numbers a, button.page-link'));
const numbered = candidates.filter(el => /\b\d+\b/.test((el.textContent || '').trim()) && !el.closest('[aria-disabled="true"], .disabled'));
const nexters = candidates.filter(el => /(next|»|›)/i.test(el.textContent || el.getAttribute('aria-label') || ''));
return { numbered, nexters };
}
function looksFeeLine(line) {
return /(fee|sem|semester|year|₹|rs\.?|amount)/i.test(line);
}
async function sweepTabsAndAccordions() {
const main = selectMainContainer();
const items = Array.from(document.querySelectorAll('[data-toggle="tab"], [data-bs-toggle="tab"], [role="tab"], .tab-link, .accordion-button'));
for (const el of items) {
try {
const prev = getContainerSignature(main);
el.click();
await new Promise(r => setTimeout(r, 80));
await waitForContentMutation(main, prev, 800);
} catch (_) {}
}
}
async function sweepPaginationAndCollect(includeHidden = true, limit = 30) {
const main = selectMainContainer();
const results = new Set();
const addLines = (text) => {
if (!text) return;
const lines = text.split(/\n+/).map(s => s.trim()).filter(Boolean);
for (const line of lines) {
if (looksFeeLine(line)) results.add(line);
}
};
addLines(extractDomOrderedText(includeHidden));
const { numbered, nexters } = getPaginationElements();
const pageNumbers = Array.from(new Set(numbered.map(el => (el.textContent || '').trim()).filter(Boolean)))
.map(s => parseInt(s, 10))
.filter(n => !Number.isNaN(n))
.sort((a,b) => a-b)
.slice(0, limit);
if (pageNumbers.length > 1) {
for (const n of pageNumbers) {
const el = numbered.find(e => parseInt((e.textContent||'').trim(),10) === n);
if (!el) continue;
try {
const prev = getContainerSignature(main);
el.click();
await new Promise(r => setTimeout(r, 150));
await waitForContentMutation(main, prev, 1500);
addLines(extractDomOrderedText(includeHidden));
} catch (_) {}
}
return Array.from(results).join('\n');
}
// Fallback: fetch other pages by following pagination hrefs
const hrefs = Array.from(new Set(numbered
.map(el => el.getAttribute('href') || '')
.filter(h => h && h !== '#' && !/^javascript/i.test(h))
.map(h => {
try { return new URL(h, window.location.href).toString(); } catch (_) { return null; }
})
.filter(Boolean)));
if (hrefs.length > 1) {
const parser = new DOMParser();
const toFetch = hrefs.slice(0, limit);
for (const url of toFetch) {
try {
const res = await fetch(url, { credentials: 'include', cache: 'no-store' });
if (!res.ok) continue;
const html = await res.text();
const doc = parser.parseFromString(html, 'text/html');
const feesOnly = extractFeesFromParsedDoc(doc);
if (feesOnly && feesOnly.length) {
addLines(feesOnly);
} else {
const text = extractDomOrderedTextFromDoc(doc);
addLines(text);
}
} catch (_) {}
}
return Array.from(results).join('\n');
}
let safety = limit;
while (safety-- > 0 && nexters[0]) {
try {
const prev = getContainerSignature(main);
nexters[0].click();
await new Promise(r => setTimeout(r, 150));
const changed = await waitForContentMutation(main, prev, 1500);
if (!changed) break;
addLines(extractDomOrderedText(includeHidden));
} catch (_) { break; }
}
return Array.from(results).join('\n');
}
// In-page dynamic pagination collector (click through tabs/numbers within same URL)
function discoverInPagePagers() {
const main = selectMainContainer();
const els = Array.from(main.querySelectorAll('a,button,[role="tab"], .page-link, .page-numbers a, .pagination a, .page-item, [data-page], [data-index]'));
const numbered = [];
const nexters = [];
els.forEach(el => {
const t = (el.textContent || '').trim();
if (/^\d+$/.test(t)) numbered.push(el);
else if (/(next|»|›)/i.test(t) || el.getAttribute('rel') === 'next') nexters.push(el);
});
return { numbered, nexters };
}
async function collectDynamicAllText(limit = 50) {
try {
const main = selectMainContainer();
const seenSigs = new Set();
const out = new Set();
const addText = (text) => {
if (!text) return;
text.split(/\n+/).forEach(s => { const t = s.trim(); if (t) out.add(t); });
};
addText(extractDomOrderedText(true));
seenSigs.add(getContainerSignature(main));
const { numbered, nexters } = discoverInPagePagers();
const pageNumbers = Array.from(new Set(numbered.map(el => parseInt((el.textContent || '').trim(), 10)).filter(n => !Number.isNaN(n))))
.sort((a, b) => a - b)
.slice(0, limit);
for (const n of pageNumbers) {
const el = numbered.find(e => parseInt((e.textContent || '').trim(), 10) === n);
if (!el) continue;
try {
const prev = getContainerSignature(main);
el.click();
await new Promise(r => setTimeout(r, 150));
const changed = await waitForContentMutation(main, prev, 1500);
if (!changed) continue;
const sig = getContainerSignature(main);
if (seenSigs.has(sig)) continue;
seenSigs.add(sig);
addText(extractDomOrderedText(true));
} catch (_) {}
}
let safety = limit;
while (safety-- > 0 && nexters[0]) {
try {
const prev = getContainerSignature(main);
nexters[0].click();
await new Promise(r => setTimeout(r, 150));
const changed = await waitForContentMutation(main, prev, 1500);
if (!changed) break;
const sig = getContainerSignature(main);
if (seenSigs.has(sig)) break;
seenSigs.add(sig);
addText(extractDomOrderedText(true));
} catch (_) { break; }
}
return Array.from(out).join('\n');
} catch (_) {
return extractDomOrderedText(true);
}
}
// Special handling for Sharda course-fee (two-phase state machine)
function isShardaCourseFeePage() {
try {
const u = new URL(location.href);
return /sharda\.ac\.in$/i.test(u.hostname) && u.pathname.replace(/\/+$/,'') === '/course-fee';
} catch (_) { return false; }
}
function _textMatch(el, re) {
try { return re.test((el.textContent || el.innerText || '').trim()); } catch(_) { return false; }
}
function findListRootSharda() {
try {
const pool = Array.from(document.querySelectorAll('main, #content, .content, #main, article, .container, .row, body *'));
let best = null, bestScore = 0;
for (const c of pool.slice(0, 500)) {
const btns = c.querySelectorAll('a,button');
let score = 0;
btns.forEach(b => { if (_textMatch(b, /(yearly\s*fee|semester\s*fee)/i)) score++; });
if (score > bestScore) { bestScore = score; best = c; }
}
return best || selectMainContainer();
} catch (_) { return selectMainContainer(); }
}
function getPagerNear(root) {
const zones = new Set();
let a = root;
for (let i = 0; i < 4 && a; i++, a = a.parentElement) zones.add(a);
const all = Array.from(document.querySelectorAll('ul.pagination, .pagination, nav[aria-label*="pagination" i], .page-numbers'));
const cand = all.filter(p => {
let x = p, d = 0;
while (x && d < 6) { if (zones.has(x)) return true; x = x.parentElement; d++; }
return false;
});
const pager = cand[0] || all[0] || null;
if (!pager) return { pager: null, numbers: [], next: null };
const anchors = Array.from(pager.querySelectorAll('a,button'));
const numbers = anchors.filter(el => /^\d+$/.test((el.textContent || '').trim()));
const next = anchors.find(el => /(next|»|›)/i.test(el.textContent || el.getAttribute('aria-label') || ''));
return { pager, numbers, next };
}
function getActivePageNumberNear(root) {
try {
const { pager } = getPagerNear(root);
if (!pager) return null;
const cur = pager.querySelector('.active, [aria-current="page"], .current');
const t = (cur?.textContent || '').trim();
const n = parseInt(t, 10);
return Number.isFinite(n) ? n : null;
} catch (_) { return null; }
}
async function clickPagerNumberNear(root, number, timeout = 2500) {
const { pager } = getPagerNear(root);
if (!pager) return false;
const el = Array.from(pager.querySelectorAll('a,button')).find(a => parseInt((a.textContent || '').trim(), 10) === number);
if (!el) return false;
const prev = getContainerSignature(root);
el.click();
await new Promise(r => setTimeout(r, 120));
const changed = await waitForContentMutation(root, prev, timeout);
return !!changed;
}
async function drillDownFeesInList(root) {
const toggles = Array.from(root.querySelectorAll('a,button')).filter(el => _textMatch(el, /(yearly\s*fee|semester\s*fee)/i));
const seenParents = new WeakSet();
for (const el of toggles) {
try {
const parent = el.closest('.card, li, .course, .program, .programme, .row, .col') || root;
if (seenParents.has(parent)) continue;
seenParents.add(parent);
const prev = getContainerSignature(parent);
el.click();
await new Promise(r => setTimeout(r, 80));
await waitForContentMutation(parent, prev, 900);
} catch (_) {}
}
}
async function scrapeShardaCourseFees(options = {}) {
const maxPages = typeof options.maxPages === 'number' ? options.maxPages : 50;
const listRoot = findListRootSharda();
const out = new Set();
const addText = (txt) => {
if (!txt) return;
txt.split(/\n+/).forEach(s => { const t = s.trim(); if (t) out.add(t); });
};
const visited = new Set();
let safety = maxPages;
let active = getActivePageNumberNear(listRoot);
if (!Number.isFinite(active) || active <= 0) active = 1;
while (safety-- > 0) {
if (!visited.has(active)) {
await drillDownFeesInList(listRoot);
addText(extractDomOrderedTextWithin(listRoot, true));
visited.add(active);
}
const { pager } = getPagerNear(listRoot);
if (!pager) break;
const desired = active + 1;
// Prefer clicking the numeric next page (active+1); fallback to "Next"
const buttons = Array.from(pager.querySelectorAll('a,button'));
let target = buttons.find(a => parseInt((a.textContent || '').trim(), 10) === desired) ||
buttons.find(a => /(next|»|›)/i.test(a.textContent || a.getAttribute('aria-label') || ''));
if (!target) break;
const prevSig = getContainerSignature(listRoot);
target.click();
await new Promise(r => setTimeout(r, 120));
const changed = await waitForContentMutation(listRoot, prevSig, 2500);
if (!changed) break;
let newActive = getActivePageNumberNear(listRoot);
if (!Number.isFinite(newActive)) newActive = active;
// If pager reflows and we didn't advance, try to locate the smallest unseen number > current
if (newActive <= active || visited.has(newActive)) {
const nums = buttons
.map(a => parseInt((a.textContent || '').trim(), 10))
.filter(n => Number.isFinite(n) && !visited.has(n));
const candidates = nums.filter(n => n > active);
const nextNum = (candidates.length ? Math.min(...candidates) : Math.min(...nums.filter(n => !visited.has(n)) || [NaN]));
if (Number.isFinite(nextNum) && nextNum !== active) {
const el = buttons.find(a => parseInt((a.textContent || '').trim(), 10) === nextNum);
if (el) {
const sig2 = getContainerSignature(listRoot);
el.click();
await new Promise(r => setTimeout(r, 120));
await waitForContentMutation(listRoot, sig2, 2500);
newActive = getActivePageNumberNear(listRoot) ?? nextNum;
}
}
}
if (newActive === active || visited.has(newActive)) break;
active = newActive;
}
return Array.from(out).join('\n');
}
function extractDomOrderedTextFromDoc(doc) {
try {
const selector = ['h1','h2','h3','h4','h5','h6','p','li','table','blockquote','dt','dd','figcaption'].join(',');
const nodes = Array.from(doc.querySelectorAll(selector));
const lines = [];
let last = '';
for (const node of nodes) {
if (node.tagName === 'TABLE') {
const trs = node.querySelectorAll('tr');
trs.forEach(tr => {
const cells = Array.from(tr.querySelectorAll('th,td')).map(c => (c.textContent||'').replace(/\s+/g,' ').trim()).filter(Boolean);
if (cells.length === 2) lines.push(`${cells[0]}: ${cells[1]}`);
else if (cells.length > 0) lines.push(cells.join(' | '));
});
continue;
}
let text = (node.textContent || '').replace(/\s+/g,' ').trim();
if (!text) continue;
if (node.tagName === 'LI') text = `• ${text}`;
if (text !== last) { lines.push(text); last = text; }
}
return lines.join('\n');
} catch (_) {
return '';
}
}
// Parse inline JSON variable `allCourses = [...]` to capture complete fee dataset
function extractCoursesFromInlineJSON() {
try {
const scripts = Array.from(document.querySelectorAll('script'));
let jsonText = '';
for (const s of scripts) {
const t = s.textContent || '';
if (!t) continue;
if (/allCourses\s*=\s*\[/i.test(t)) {
const m = t.match(/allCourses\s*=\s*(\[[\s\S]*?\]);/i);
if (m && m[1]) { jsonText = m[1]; break; }
// fallback: bracket match
const start = t.indexOf('[');
if (start !== -1) {
let depth = 0;
for (let i = start; i < t.length; i++) {
const ch = t[i];
if (ch === '[') depth++;
else if (ch === ']') { depth--; if (depth === 0) { jsonText = t.slice(start, i + 1); break; } }
}
if (jsonText) break;
}
}
}
if (!jsonText) return '';
let arr;
try { arr = JSON.parse(jsonText); } catch (_) { return ''; }
if (!Array.isArray(arr) || arr.length === 0) return '';
const lines = [];
const asMoney = (v) => {
if (!v || v === '0') return '';
return v;
};
for (const item of arr) {
const name = (item.course_name || item.title || '').trim();
if (!name) continue;
const yearly = [
asMoney(item.fyear_fee) && `1st Year ${item.fyear_fee}`,
asMoney(item.syear_fee) && `2nd Year ${item.syear_fee}`,
asMoney(item.tyear_fee) && `3rd Year ${item.tyear_fee}`,
asMoney(item.ftyear_fee) && `4th Year ${item.ftyear_fee}`,
asMoney(item.fiftyear_fee) && `5th Year ${item.fiftyear_fee}`,
asMoney(item.sixyear_fee) && `6th Year ${item.sixyear_fee}`
].filter(Boolean).join(' | ');
const sem = [
asMoney(item.firstsem_fee) && `1st Sem ${item.firstsem_fee}`,
asMoney(item.secondsem_fee) && `2nd Sem ${item.secondsem_fee}`,
asMoney(item.thirdsem_fee) && `3rd Sem ${item.thirdsem_fee}`,
asMoney(item.fourthsem_fee) && `4th Sem ${item.fourthsem_fee}`,
asMoney(item.fifthsem_fee) && `5th Sem ${item.fifthsem_fee}`,
asMoney(item.sixsem_fee) && `6th Sem ${item.sixsem_fee}`,
asMoney(item.seventhsem_fee) && `7th Sem ${item.seventhsem_fee}`,
asMoney(item.eightsem_fee) && `8th Sem ${item.eightsem_fee}`,
asMoney(item.ninethsem_fee) && `9th Sem ${item.ninethsem_fee}`,
asMoney(item.tenthsem_fee) && `10th Sem ${item.tenthsem_fee}`,
asMoney(item.eleventhsem_fee) && `11th Sem ${item.eleventhsem_fee}`,
asMoney(item.twelfth_fee) && `12th Sem ${item.twelfth_fee}`
].filter(Boolean).join(' | ');
if (yearly) lines.push(`${name} — Yearly Fee ${yearly}`);
if (sem) lines.push(`${name} — Semester Fee ${sem}`);
}
return lines.join('\n');
} catch (_) { return ''; }
}
function extractCoursesFromWindowGlobal() {
try {
const arr = (window && window.allCourses) ? window.allCourses : null;
if (!Array.isArray(arr) || arr.length === 0) return '';
const asMoney = (v) => { if (!v || v === '0') return ''; return v; };
const lines = [];
for (const item of arr) {
const name = (item.course_name || item.title || '').trim();
if (!name) continue;
const yearly = [
asMoney(item.fyear_fee) && `1st Year ${item.fyear_fee}`,
asMoney(item.syear_fee) && `2nd Year ${item.syear_fee}`,
asMoney(item.tyear_fee) && `3rd Year ${item.tyear_fee}`,
asMoney(item.ftyear_fee) && `4th Year ${item.ftyear_fee}`,
asMoney(item.fiftyear_fee) && `5th Year ${item.fiftyear_fee}`,
asMoney(item.sixyear_fee) && `6th Year ${item.sixyear_fee}`
].filter(Boolean).join(' | ');
const sem = [
asMoney(item.firstsem_fee) && `1st Sem ${item.firstsem_fee}`,
asMoney(item.secondsem_fee) && `2nd Sem ${item.secondsem_fee}`,
asMoney(item.thirdsem_fee) && `3rd Sem ${item.thirdsem_fee}`,
asMoney(item.fourthsem_fee) && `4th Sem ${item.fourthsem_fee}`,
asMoney(item.fifthsem_fee) && `5th Sem ${item.fifthsem_fee}`,
asMoney(item.sixsem_fee) && `6th Sem ${item.sixsem_fee}`,
asMoney(item.seventhsem_fee) && `7th Sem ${item.seventhsem_fee}`,
asMoney(item.eightsem_fee) && `8th Sem ${item.eightsem_fee}`,
asMoney(item.ninethsem_fee) && `9th Sem ${item.ninethsem_fee}`,
asMoney(item.tenthsem_fee) && `10th Sem ${item.tenthsem_fee}`,
asMoney(item.eleventhsem_fee) && `11th Sem ${item.eleventhsem_fee}`,
asMoney(item.twelfth_fee) && `12th Sem ${item.twelfth_fee}`
].filter(Boolean).join(' | ');
if (yearly) lines.push(`${name} — Yearly Fee ${yearly}`);
if (sem) lines.push(`${name} — Semester Fee ${sem}`);
}
return lines.join('\n');
} catch (_) { return ''; }
}
// Extract in DOM order to preserve context for LLMs
function extractDomOrderedText(includeHidden = false) {
const selector = [
'h1','h2','h3','h4','h5','h6',
'p','li','table','blockquote','dt','dd','figcaption'
].join(',');
const nodes = Array.from(document.querySelectorAll(selector));
const lines = [];
let last = '';
nodes.forEach(node => {
if (!shouldIncludeElement(node, includeHidden)) return;
if (node.tagName === 'TABLE') {
const tblRows = [];
const trs = node.querySelectorAll('tr');
trs.forEach(tr => {
const cells = Array.from(tr.querySelectorAll('th,td'))
.map(c => cleanText(c.textContent).replace(/\s*:\s*$/,'').replace(/^[:\-\s]+/,''))
.filter(Boolean);
if (cells.length === 2) {
tblRows.push(`${cells[0]}: ${cells[1]}`);
} else if (cells.length > 0) {
tblRows.push(cells.join(' | '));
}
});
if (tblRows.length) {
tblRows.forEach(row => {
if (row && row !== last) {
lines.push(row);
last = row;
}
});
}
return;
}
let text = cleanText(node.textContent || '');
if (!text) return;
if (node.tagName === 'LI') {
text = `• ${text}`;
}
if (text && text !== last) {
lines.push(text);
last = text;
}
});
return lines.join('\n');
}
// Extract course/fee tables from a parsed Document (used for view-source:)
function extractFeesFromParsedDoc(doc) {
try {
const tables = Array.from(doc.querySelectorAll('table'));
const feeLines = [];
tables.forEach(table => {
const rows = Array.from(table.querySelectorAll('tr'));
if (rows.length < 2) return;
const headerCells = Array.from(rows[0].querySelectorAll('th,td')).map(c => (c.textContent||'').trim().toLowerCase());
const headerJoined = headerCells.join(' ');
// Heuristics: identify fee tables
const looksLikeFees = /fee|year|semester/.test(headerJoined) ||
(headerCells.includes('programme') || headerCells.includes('program') || headerCells.includes('course'));
if (!looksLikeFees) return;
// Collect column indices
const colNames = headerCells.map(h => h.replace(/\s+/g,' '));
feeLines.push('');
rows.slice(1).forEach(r => {
const cols = Array.from(r.querySelectorAll('td,th')).map(c => (c.textContent||'').replace(/\s+/g,' ').trim());
if (cols.every(v => !v)) return;
let name = cols[0];
// Some tables may have program name in second column
if (/^(s\.?no\.?|serial|#)$/i.test(colNames[0] || '')) {
name = cols[1] || name;
}
const parts = [];
for (let i=0; i<cols.length; i++) {
const h = colNames[i] || `col${i+1}`;
if (/^(s\.?no\.?|serial|#)$/i.test(h)) continue;
if (i === 0 || (i === 1 && name === cols[1] && /programme|program|course/.test(colNames[1]||''))) continue;
const val = cols[i];
if (!val) continue;
parts.push(`${h}: ${val}`);
}
if (name && parts.length) {
feeLines.push(`${name} — ${parts.join(', ')}`);
} else if (name) {
feeLines.push(name);
}
});
});
return feeLines.filter(Boolean).join('\n').trim();
} catch (_) {
return '';
}
}
// Collect embedded PDF URLs from the page (embed/object/iframe/anchors)
function collectEmbeddedPdfUrls() {
try {
const out = [];
const seen = new Set();
const base = location.href;
const pushAbs = (u) => {
try {
const abs = new URL(u, base).toString();
const key = abs.split('#')[0];
if (seen.has(key)) return;
if (/\.pdf(?:$|[?#])/i.test(abs)) {
seen.add(key); out.push(abs);
}
} catch (_) {}
};
const embeds = document.querySelectorAll('embed[type="application/pdf"], object[type="application/pdf"], iframe[src$=".pdf"], iframe[src*=".pdf?"], iframe[src*=".pdf#"]');
embeds.forEach(el => {
const src = el.getAttribute('src') || el.getAttribute('data') || '';
if (src) pushAbs(src);
});
// Anchor fallbacks
document.querySelectorAll('a[href$=".pdf"], a[href*=".pdf?"], a[href*=".pdf#"]').forEach(a => {
const href = a.getAttribute('href') || '';
if (href) pushAbs(href);
});
return out;
} catch (_) { return []; }
}
// Derive real PDF URL when viewing via Chrome/Edge built-in PDF viewer
function derivePdfUrlFromLocation() {
try {
const tabUrl = window.location.href || '';
if (!tabUrl) return '';
const u = new URL(tabUrl);
// Direct PDF only if pathname ends with .pdf
if (u.pathname && u.pathname.toLowerCase().endsWith('.pdf')) {
return u.toString();
}
// Chrome/Edge PDF viewer: src= or file= query contains the real URL
if (u.protocol === 'chrome-extension:' || u.protocol === 'edge:') {
const q = u.searchParams.get('src') || u.searchParams.get('file') || '';
if (!q) return '';
const qUrl = new URL(q, tabUrl);
if ((qUrl.protocol === 'http:' || qUrl.protocol === 'https:') &&
qUrl.pathname.toLowerCase().endsWith('.pdf')) {
return qUrl.toString();
}
}
return '';
} catch (_) {
return '';
}
}
// Build a full-page structured extraction with metadata and sections
function extractStructuredPage(options = {}) {
const {
includeHidden = false,
excludeBoilerplate = false,
includeMetadata = true
} = options || {};
const lines = [];
// Helpers
function getMetaByName(name) {
const el = document.querySelector(`meta[name="${name}"]`);
return el ? (el.getAttribute('content') || '').trim() : '';
}
function getMetaByProperty(prop) {
const el = document.querySelector(`meta[property="${prop}"]`);
return el ? (el.getAttribute('content') || '').trim() : '';
}
function isBoilerplate(el) {
if (!excludeBoilerplate) return false;
const boilerSelectors = [
'header', 'footer', 'nav', 'aside',
'[role="navigation"]', '[role="banner"]', '[role="contentinfo"]',
'[class*="nav"]', '[id*="nav"]', '[class*="menu"]', '[class*="footer"]', '[id*="footer"]',
'[class*="sidebar"]', '.ads', '[class*="ad-" ]', '[id*="ad-" ]'
];
try {
return boilerSelectors.some(sel => el.closest && el.closest(sel));
} catch (_) { return false; }
}
// Title
const title = (document.querySelector('title')?.textContent || document.title || '').trim();
if (title) {
lines.push('== Title ==');
lines.push(title);
lines.push('');
}
// Metadata
if (includeMetadata) {
const metaLines = [];
const desc = getMetaByName('description');
const ogTitle = getMetaByProperty('og:title');
const ogDesc = getMetaByProperty('og:description');
const ogImage = getMetaByProperty('og:image');
const ogType = getMetaByProperty('og:type');
const ogUrl = getMetaByProperty('og:url');
if (desc) metaLines.push(`Description: ${desc}`);
if (ogTitle) metaLines.push(`OG Title: ${ogTitle}`);
if (ogDesc) metaLines.push(`OG Description: ${ogDesc}`);
if (ogImage) metaLines.push(`OG Image: ${ogImage}`);
if (ogType) metaLines.push(`OG Type: ${ogType}`);
if (ogUrl) metaLines.push(`OG URL: ${ogUrl}`);
if (metaLines.length) {
lines.push('== Metadata ==');
lines.push(...metaLines);
lines.push('');
}
}
// Embedded PDFs on page
try {
const pdfs = collectEmbeddedPdfUrls();
if (pdfs.length) {
lines.push('== Embedded PDFs ==');
pdfs.slice(0, 50).forEach((u, i) => lines.push(`PDF ${i+1}: ${u}`));
lines.push('');
}
} catch (_) {}
// Headings
const headingNodes = Array.from(document.querySelectorAll('h1,h2,h3,h4,h5,h6'));
const headingOut = [];
headingNodes.forEach(h => {
if (!shouldIncludeElement(h, includeHidden)) return;
if (isBoilerplate(h)) return;
if (isInHeaderFooterZone(h)) return;
const txt = cleanText(h.textContent || '');
if (!txt) return;
headingOut.push(`${h.tagName.toUpperCase()}: ${txt}`);
});
if (headingOut.length) {
lines.push('== Headings ==');
lines.push(...headingOut);
lines.push('');
}
// Paragraphs and blockquotes
const pbNodes = Array.from(document.querySelectorAll('p,blockquote'));
const pbOut = [];
pbNodes.forEach(n => {
if (!shouldIncludeElement(n, includeHidden)) return;
if (isBoilerplate(n)) return;
if (isInHeaderFooterZone(n)) return;
const txt = cleanText(n.textContent || '');
if (!txt) return;
const prefix = n.tagName === 'BLOCKQUOTE' ? '> ' : '';
pbOut.push(prefix + txt);
});
if (pbOut.length) {
lines.push('== Paragraphs ==');
lines.push(...pbOut);
lines.push('');
}
// Lists (ul/ol)
const listItems = Array.from(document.querySelectorAll('li'));
const listOut = [];
listItems.forEach(li => {
if (!shouldIncludeElement(li, includeHidden)) return;
if (isBoilerplate(li)) return;
if (isInHeaderFooterZone(li)) return;
const txt = cleanText(li.textContent || '');
if (!txt) return;
listOut.push(`• ${txt}`);
});
if (listOut.length) {
lines.push('== Lists ==');
lines.push(...listOut);
lines.push('');
}
// Tables (raw) + Course Fees synthesis (group by nearest heading)
const tableNodes = Array.from(document.querySelectorAll('table'));
const tableLines = [];
const feeSynthesis = [];
function nearestHeading(el) {
let sib = el;
let hops = 0;
while (sib && hops < 10) {
sib = sib.previousElementSibling || sib.parentElement;
hops += 1;
if (!sib) break;
if (/^H[1-6]$/.test(sib.tagName)) {
return cleanText(sib.textContent || '');
}
}
return '';
}
tableNodes.forEach(table => {
if (!includeHidden && !isElementVisible(table)) return;
if (isUnwantedElement(table) || isBoilerplate(table)) return;
const rows = [];
const trList = table.querySelectorAll('tr');
trList.forEach(tr => {
const cells = Array.from(tr.querySelectorAll('th, td'))
.map(cell => cleanText(cell.textContent).replace(/\s*:\s*$/,'').replace(/^[:\-\s]+/, ''))
.filter(t => t.length > 0);
if (cells.length > 0) rows.push(cells);
});
if (rows.length === 0) return;
// Raw table dump for completeness
const captionEl = table.querySelector('caption');
if (captionEl) tableLines.push(`# ${cleanText(captionEl.textContent || '')}`);