-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeb Page Inspector v2.js
More file actions
1964 lines (1647 loc) · 67 KB
/
Web Page Inspector v2.js
File metadata and controls
1964 lines (1647 loc) · 67 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
/*
========================================
Advanced Web Page Inspector & Diagnostic Tool
A comprehensive analysis tool for modern web pages
Designed to reveal DOM structure, frameworks, components, and technical details
========================================
*/
class WebPageInspector {
constructor() {
this.results = {
timestamp: new Date().toISOString(),
url: window.location.href,
userAgent: navigator.userAgent,
viewport: {
width: window.innerWidth,
height: window.innerHeight
},
analysis: {}
};
this.startTime = performance.now();
}
// Main analysis orchestrator
async runFullAnalysis() {
console.log('🚀 Starting Advanced Web Page Analysis...');
console.log('================================================');
try {
// Core DOM analysis
await this.analyzePageStructure();
await this.analyzeFrameworks();
await this.analyzeWebComponents();
await this.analyzeShadowDOM();
await this.analyzeIframes();
await this.analyzeScripts();
await this.analyzeStylesheets();
await this.analyzeMetadata();
await this.analyzeSecurity();
await this.analyzePerformance();
await this.analyzeAccessibility();
await this.analyzeDynamicContent();
await this.analyzeEventListeners();
await this.analyzeStorage();
await this.analyzeNetwork();
// Summary and recommendations
this.generateSummary();
this.generateRecommendations();
const endTime = performance.now();
console.log(`\n⏱️ Analysis completed in ${(endTime - this.startTime).toFixed(2)}ms`);
return this.results;
} catch (error) {
console.error('❌ Analysis failed:', error);
return { error: error.message, partialResults: this.results };
}
}
// 1. Page Structure Analysis
async analyzePageStructure() {
console.log('\n📋 ANALYZING PAGE STRUCTURE');
console.log('============================');
const structure = {
doctype: document.doctype ? document.doctype.name : 'None',
documentElement: document.documentElement.tagName,
head: {
title: document.title || 'No title',
metaCount: document.querySelectorAll('meta').length,
linkCount: document.querySelectorAll('link').length,
scriptCount: document.querySelectorAll('head script').length
},
body: {
id: document.body.id || 'No ID',
classes: [...document.body.classList],
childElementCount: document.body.childElementCount,
totalElements: document.querySelectorAll('*').length
},
semanticElements: this.countSemanticElements(),
customElements: this.findCustomElements(),
dataAttributes: this.analyzeDataAttributes()
};
console.log('Document Type:', structure.doctype);
console.log('Total Elements:', structure.body.totalElements);
console.log('Body Classes:', structure.body.classes);
console.log('Custom Elements Found:', structure.customElements.length);
console.log('Semantic Elements:', structure.semanticElements);
this.results.analysis.structure = structure;
}
countSemanticElements() {
const semanticTags = ['header', 'nav', 'main', 'article', 'section', 'aside', 'footer', 'figure', 'figcaption', 'details', 'summary'];
const counts = {};
semanticTags.forEach(tag => {
counts[tag] = document.querySelectorAll(tag).length;
});
return counts;
}
findCustomElements() {
const allElements = document.querySelectorAll('*');
const customElements = [];
const standardTags = new Set(['DIV', 'SPAN', 'P', 'A', 'IMG', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'LI', 'HEADER', 'FOOTER', 'NAV', 'MAIN', 'SECTION', 'ARTICLE', 'ASIDE', 'BUTTON', 'INPUT', 'FORM', 'TABLE', 'TR', 'TD', 'TH', 'TBODY', 'THEAD', 'SCRIPT', 'STYLE', 'LINK', 'META', 'TITLE', 'HTML', 'HEAD', 'BODY']);
allElements.forEach(el => {
if (!standardTags.has(el.tagName) && el.tagName.includes('-')) {
customElements.push({
tagName: el.tagName,
id: el.id,
classes: [...el.classList],
attributes: [...el.attributes].map(attr => `${attr.name}="${attr.value.substring(0, 50)}${attr.value.length > 50 ? '...' : ''}"`),
hasShadowRoot: !!el.shadowRoot,
innerHTML: el.innerHTML.substring(0, 200) + (el.innerHTML.length > 200 ? '...' : '')
});
}
});
return customElements;
}
analyzeDataAttributes() {
const allElements = document.querySelectorAll('*');
const dataAttributes = new Set();
allElements.forEach(el => {
[...el.attributes].forEach(attr => {
if (attr.name.startsWith('data-')) {
dataAttributes.add(attr.name);
}
});
});
return {
uniqueDataAttributes: [...dataAttributes],
count: dataAttributes.size
};
}
// 2. Framework Detection
async analyzeFrameworks() {
console.log('\n🏗️ ANALYZING FRAMEWORKS & LIBRARIES');
console.log('===================================');
const frameworks = {
detected: [],
indicators: {},
globalObjects: this.checkGlobalObjects(),
cssFrameworks: this.detectCSSFrameworks(),
buildTools: this.detectBuildTools()
};
// Framework detection patterns
const detectionPatterns = {
'React': () => window.React || document.querySelector('[data-reactroot]') || document.querySelector('[data-react-helmet]'),
'Vue.js': () => window.Vue || document.querySelector('[data-v-]') || document.querySelector('[v-]'),
'Angular': () => window.ng || document.querySelector('[ng-]') || document.querySelector('[data-ng-]'),
'Nuxt.js': () => window.__NUXT__ || document.querySelector('#__nuxt'),
'Next.js': () => window.__NEXT_DATA__ || document.querySelector('#__next'),
'jQuery': () => window.jQuery || window.$,
'Lit': () => window.lit || document.querySelector('[data-lit]'),
'Alpine.js': () => window.Alpine || document.querySelector('[x-data]'),
'Svelte': () => document.querySelector('[svelte-]'),
'Ember.js': () => window.Ember || document.querySelector('[data-ember-]'),
'Backbone.js': () => window.Backbone,
'D3.js': () => window.d3,
'Three.js': () => window.THREE,
'GSAP': () => window.gsap || window.TweenMax,
'Chart.js': () => window.Chart,
'Lodash': () => window._ && window._.VERSION,
'Moment.js': () => window.moment,
'Bootstrap': () => window.bootstrap || document.querySelector('.bootstrap') || document.querySelector('[class*="bs-"]'),
'Tailwind CSS': () => document.querySelector('[class*="bg-"]') && document.querySelector('[class*="text-"]'),
'Material-UI': () => window.MaterialUI || document.querySelector('[class*="Mui"]'),
'Ant Design': () => window.antd || document.querySelector('[class*="ant-"]')
};
Object.entries(detectionPatterns).forEach(([name, detector]) => {
try {
const detected = detector();
if (detected) {
frameworks.detected.push(name);
frameworks.indicators[name] = typeof detected === 'object' ? 'Object detected' : detected.toString().substring(0, 100);
}
} catch (e) {
// Silent fail for framework detection
}
});
console.log('Detected Frameworks:', frameworks.detected);
console.log('CSS Frameworks:', frameworks.cssFrameworks);
console.log('Global Objects:', Object.keys(frameworks.globalObjects));
this.results.analysis.frameworks = frameworks;
}
checkGlobalObjects() {
const commonGlobals = ['React', 'Vue', 'Angular', 'jQuery', '$', 'gsap', 'd3', 'THREE', 'Chart', '_', 'moment', 'axios', 'fetch'];
const detected = {};
commonGlobals.forEach(obj => {
if (window[obj]) {
detected[obj] = {
type: typeof window[obj],
version: window[obj].version || window[obj].VERSION || 'Unknown',
properties: Object.keys(window[obj]).slice(0, 10)
};
}
});
return detected;
}
detectCSSFrameworks() {
const frameworks = [];
const stylesheets = [...document.styleSheets];
// Check for CSS framework indicators in classes
const allElements = document.querySelectorAll('*');
const classPatterns = {
'Bootstrap': /\b(container|row|col-|btn-|card-|navbar-|modal-)\w*/,
'Tailwind CSS': /\b(bg-|text-|p-|m-|flex|grid|w-|h-)\w*/,
'Bulma': /\b(is-|has-|column|level|hero|navbar)\w*/,
'Foundation': /\b(foundation|grid-|cell|callout)\w*/,
'Materialize': /\b(materialize|btn|card|collection)\w*/,
'Semantic UI': /\b(ui |semantic|button|menu|dropdown)\w*/,
'Material-UI': /\b(Mui|makeStyles|withStyles)\w*/,
'Ant Design': /\bant-\w*/
};
Object.entries(classPatterns).forEach(([framework, pattern]) => {
let found = false;
for (let el of allElements) {
if (pattern.test(el.className)) {
found = true;
break;
}
}
if (found) frameworks.push(framework);
});
return frameworks;
}
detectBuildTools() {
const indicators = [];
// Check for build tool indicators
if (document.querySelector('script[src*="webpack"]')) indicators.push('Webpack');
if (document.querySelector('script[src*="vite"]')) indicators.push('Vite');
if (document.querySelector('script[src*="parcel"]')) indicators.push('Parcel');
if (window.__webpack_require__) indicators.push('Webpack (runtime)');
if (window.__vite__) indicators.push('Vite (runtime)');
return indicators;
}
// 3. Web Components Analysis
async analyzeWebComponents() {
console.log('\n🧩 ANALYZING WEB COMPONENTS');
console.log('============================');
const components = {
customElements: [],
shadowRoots: [],
autonomousElements: [],
customizedBuiltIns: []
};
// Find all custom elements
const allElements = document.querySelectorAll('*');
allElements.forEach(el => {
// Check if it's a custom element (contains hyphen)
if (el.tagName.includes('-')) {
const componentInfo = {
tagName: el.tagName,
id: el.id,
classes: [...el.classList],
attributes: [...el.attributes].map(attr => ({
name: attr.name,
value: attr.value.length > 100 ? attr.value.substring(0, 100) + '...' : attr.value
})),
hasShadowRoot: !!el.shadowRoot,
shadowRootMode: el.shadowRoot ? el.shadowRoot.mode : null,
innerHTML: el.innerHTML.substring(0, 300) + (el.innerHTML.length > 300 ? '...' : ''),
computedStyle: {
display: getComputedStyle(el).display,
position: getComputedStyle(el).position,
width: getComputedStyle(el).width,
height: getComputedStyle(el).height
},
customProperties: this.getCustomElementProperties(el),
events: this.getElementEventListeners(el)
};
components.customElements.push(componentInfo);
// Analyze shadow root if present
if (el.shadowRoot) {
components.shadowRoots.push(this.analyzeShadowRoot(el, el.shadowRoot));
}
}
});
console.log('Custom Elements Found:', components.customElements.length);
console.log('Shadow Roots Found:', components.shadowRoots.length);
components.customElements.forEach(comp => {
console.log(` - ${comp.tagName}: ${comp.hasShadowRoot ? 'Has Shadow DOM' : 'No Shadow DOM'}`);
});
this.results.analysis.webComponents = components;
}
getCustomElementProperties(element) {
const props = {};
const allProps = Object.getOwnPropertyNames(element);
// Filter out standard DOM properties
const standardProps = ['id', 'className', 'innerHTML', 'outerHTML', 'tagName', 'nodeName', 'nodeType'];
const customProps = allProps.filter(prop =>
!prop.startsWith('_') &&
!standardProps.includes(prop) &&
typeof element[prop] !== 'function'
);
customProps.forEach(prop => {
try {
const value = element[prop];
props[prop] = {
type: typeof value,
value: typeof value === 'object' ? '[Object]' : String(value).substring(0, 100)
};
} catch (e) {
props[prop] = { type: 'unknown', value: 'Access denied' };
}
});
return props;
}
// 4. Shadow DOM Deep Analysis
async analyzeShadowDOM() {
console.log('\n🌑 ANALYZING SHADOW DOM');
console.log('=======================');
const shadowAnalysis = {
shadowRoots: [],
totalShadowElements: 0,
shadowStyles: [],
shadowScripts: []
};
// Find all elements with shadow roots
const allElements = document.querySelectorAll('*');
allElements.forEach(el => {
if (el.shadowRoot) {
const analysis = this.analyzeShadowRoot(el, el.shadowRoot);
shadowAnalysis.shadowRoots.push(analysis);
shadowAnalysis.totalShadowElements += analysis.elementCount;
}
});
console.log('Shadow Roots Found:', shadowAnalysis.shadowRoots.length);
console.log('Total Shadow Elements:', shadowAnalysis.totalShadowElements);
this.results.analysis.shadowDOM = shadowAnalysis;
}
analyzeShadowRoot(hostElement, shadowRoot) {
const analysis = {
host: {
tagName: hostElement.tagName,
id: hostElement.id,
classes: [...hostElement.classList]
},
mode: shadowRoot.mode,
elementCount: shadowRoot.querySelectorAll('*').length,
innerHTML: shadowRoot.innerHTML.substring(0, 500) + (shadowRoot.innerHTML.length > 500 ? '...' : ''),
styles: [],
scripts: [],
elements: {},
customElements: [],
eventListeners: []
};
// Analyze styles in shadow DOM
const shadowStyles = shadowRoot.querySelectorAll('style');
shadowStyles.forEach((style, index) => {
analysis.styles.push({
index,
content: style.textContent.substring(0, 200) + (style.textContent.length > 200 ? '...' : ''),
length: style.textContent.length
});
});
// Analyze scripts in shadow DOM
const shadowScripts = shadowRoot.querySelectorAll('script');
shadowScripts.forEach((script, index) => {
analysis.scripts.push({
index,
src: script.src || 'inline',
content: script.textContent.substring(0, 200) + (script.textContent.length > 200 ? '...' : ''),
length: script.textContent.length
});
});
// Count element types in shadow DOM
const shadowElements = shadowRoot.querySelectorAll('*');
shadowElements.forEach(el => {
const tagName = el.tagName.toLowerCase();
analysis.elements[tagName] = (analysis.elements[tagName] || 0) + 1;
// Check for nested custom elements
if (tagName.includes('-')) {
analysis.customElements.push({
tagName: el.tagName,
classes: [...el.classList],
attributes: [...el.attributes].map(attr => `${attr.name}="${attr.value}"`)
});
}
});
return analysis;
}
// 5. Iframe Analysis
async analyzeIframes() {
console.log('\n🖼️ ANALYZING IFRAMES');
console.log('====================');
const iframes = [...document.querySelectorAll('iframe')];
const analysis = {
count: iframes.length,
details: []
};
iframes.forEach((iframe, index) => {
const detail = {
index,
src: iframe.src,
id: iframe.id,
name: iframe.name,
classes: [...iframe.classList],
attributes: [...iframe.attributes].map(attr => `${attr.name}="${attr.value}"`),
dimensions: {
width: iframe.width || getComputedStyle(iframe).width,
height: iframe.height || getComputedStyle(iframe).height
},
loading: iframe.loading,
sandbox: iframe.sandbox.toString(),
allowfullscreen: iframe.allowFullscreen,
contentAccessible: false
};
// Try to access iframe content (will fail for cross-origin)
try {
detail.contentDocument = !!iframe.contentDocument;
detail.contentWindow = !!iframe.contentWindow;
if (iframe.contentDocument) {
detail.contentTitle = iframe.contentDocument.title;
detail.contentURL = iframe.contentDocument.location.href;
detail.contentAccessible = true;
}
} catch (e) {
detail.crossOrigin = true;
detail.accessError = e.message;
}
analysis.details.push(detail);
});
console.log('Iframes Found:', analysis.count);
analysis.details.forEach(detail => {
console.log(` - ${detail.src || 'No src'}: ${detail.classes.join(' ')} (${detail.contentAccessible ? 'Accessible' : 'Cross-origin'})`);
});
this.results.analysis.iframes = analysis;
}
// 6. Scripts Analysis
async analyzeScripts() {
console.log('\n📜 ANALYZING SCRIPTS');
console.log('====================');
const scripts = [...document.querySelectorAll('script')];
const analysis = {
total: scripts.length,
inline: 0,
external: 0,
modules: 0,
details: [],
sources: new Set(),
content: {
totalSize: 0,
patterns: {}
}
};
scripts.forEach((script, index) => {
const detail = {
index,
src: script.src,
type: script.type || 'text/javascript',
async: script.async,
defer: script.defer,
module: script.type === 'module',
crossorigin: script.crossOrigin,
integrity: script.integrity,
nomodule: script.noModule,
contentLength: script.textContent.length,
contentPreview: script.textContent.substring(0, 200) + (script.textContent.length > 200 ? '...' : '')
};
if (script.src) {
analysis.external++;
analysis.sources.add(new URL(script.src, window.location.href).hostname);
} else {
analysis.inline++;
analysis.content.totalSize += script.textContent.length;
}
if (script.type === 'module') {
analysis.modules++;
}
analysis.details.push(detail);
});
// Convert Set to Array for serialization
analysis.sources = [...analysis.sources];
console.log('Total Scripts:', analysis.total);
console.log('External:', analysis.external, '| Inline:', analysis.inline, '| Modules:', analysis.modules);
console.log('External Sources:', analysis.sources);
this.results.analysis.scripts = analysis;
}
// 7. Stylesheets Analysis
async analyzeStylesheets() {
console.log('\n🎨 ANALYZING STYLESHEETS');
console.log('========================');
const analysis = {
links: [],
inline: [],
computed: {},
cssVariables: this.extractCSSVariables(),
animations: this.extractAnimations(),
mediaQueries: this.extractMediaQueries()
};
// Analyze link stylesheets
const linkElements = [...document.querySelectorAll('link[rel="stylesheet"]')];
linkElements.forEach((link, index) => {
analysis.links.push({
index,
href: link.href,
media: link.media,
crossorigin: link.crossOrigin,
integrity: link.integrity,
disabled: link.disabled
});
});
// Analyze inline styles
const styleElements = [...document.querySelectorAll('style')];
styleElements.forEach((style, index) => {
analysis.inline.push({
index,
content: style.textContent.substring(0, 300) + (style.textContent.length > 300 ? '...' : ''),
length: style.textContent.length,
media: style.media,
disabled: style.disabled
});
});
console.log('External Stylesheets:', analysis.links.length);
console.log('Inline Styles:', analysis.inline.length);
console.log('CSS Variables Found:', Object.keys(analysis.cssVariables).length);
console.log('Animations Found:', analysis.animations.length);
this.results.analysis.stylesheets = analysis;
}
extractCSSVariables() {
const variables = {};
const computedStyle = getComputedStyle(document.documentElement);
// Get CSS custom properties from document element
for (let property of computedStyle) {
if (property.startsWith('--')) {
variables[property] = computedStyle.getPropertyValue(property).trim();
}
}
return variables;
}
extractAnimations() {
const animations = [];
// Check for CSS animations on all elements
const allElements = document.querySelectorAll('*');
allElements.forEach(el => {
const computedStyle = getComputedStyle(el);
const animationName = computedStyle.animationName;
const transitionProperty = computedStyle.transitionProperty;
if (animationName && animationName !== 'none') {
animations.push({
element: el.tagName + (el.id ? `#${el.id}` : '') + (el.className ? `.${[...el.classList].join('.')}` : ''),
animationName,
duration: computedStyle.animationDuration,
timing: computedStyle.animationTimingFunction,
delay: computedStyle.animationDelay,
iterationCount: computedStyle.animationIterationCount
});
}
if (transitionProperty && transitionProperty !== 'none') {
animations.push({
element: el.tagName + (el.id ? `#${el.id}` : '') + (el.className ? `.${[...el.classList].join('.')}` : ''),
type: 'transition',
property: transitionProperty,
duration: computedStyle.transitionDuration,
timing: computedStyle.transitionTimingFunction,
delay: computedStyle.transitionDelay
});
}
});
return animations.slice(0, 20); // Limit to first 20 to prevent overwhelming output
}
extractMediaQueries() {
const mediaQueries = [];
[...document.styleSheets].forEach(sheet => {
try {
[...sheet.cssRules || sheet.rules].forEach(rule => {
if (rule.type === CSSRule.MEDIA_RULE) {
mediaQueries.push({
media: rule.media.mediaText,
rules: rule.cssRules.length
});
}
});
} catch (e) {
// Cross-origin stylesheets can't be accessed
}
});
return mediaQueries;
}
// 8. Metadata Analysis
async analyzeMetadata() {
console.log('\n📊 ANALYZING METADATA');
console.log('======================');
const metadata = {
title: document.title,
description: this.getMetaContent('description'),
keywords: this.getMetaContent('keywords'),
author: this.getMetaContent('author'),
viewport: this.getMetaContent('viewport'),
charset: document.characterSet,
lang: document.documentElement.lang,
dir: document.documentElement.dir,
openGraph: this.getOpenGraphData(),
twitterCard: this.getTwitterCardData(),
structuredData: this.getStructuredData(),
canonicalURL: this.getCanonicalURL(),
alternateLanguages: this.getAlternateLanguages(),
icons: this.getIcons()
};
console.log('Title:', metadata.title);
console.log('Description:', metadata.description);
console.log('Language:', metadata.lang);
console.log('Charset:', metadata.charset);
console.log('Open Graph Tags:', Object.keys(metadata.openGraph).length);
console.log('Structured Data:', metadata.structuredData.length, 'items');
this.results.analysis.metadata = metadata;
}
getMetaContent(name) {
const meta = document.querySelector(`meta[name="${name}"], meta[property="${name}"]`);
return meta ? meta.content : null;
}
getOpenGraphData() {
const ogData = {};
const ogMetas = document.querySelectorAll('meta[property^="og:"]');
ogMetas.forEach(meta => {
const property = meta.getAttribute('property');
ogData[property] = meta.content;
});
return ogData;
}
getTwitterCardData() {
const twitterData = {};
const twitterMetas = document.querySelectorAll('meta[name^="twitter:"]');
twitterMetas.forEach(meta => {
const name = meta.getAttribute('name');
twitterData[name] = meta.content;
});
return twitterData;
}
getStructuredData() {
const scripts = document.querySelectorAll('script[type="application/ld+json"]');
const structuredData = [];
scripts.forEach(script => {
try {
const data = JSON.parse(script.textContent);
structuredData.push(data);
} catch (e) {
structuredData.push({ error: 'Invalid JSON', content: script.textContent.substring(0, 100) });
}
});
return structuredData;
}
getCanonicalURL() {
const canonical = document.querySelector('link[rel="canonical"]');
return canonical ? canonical.href : null;
}
getAlternateLanguages() {
const alternates = document.querySelectorAll('link[rel="alternate"][hreflang]');
return [...alternates].map(link => ({
hreflang: link.hreflang,
href: link.href
}));
}
getIcons() {
const iconLinks = document.querySelectorAll('link[rel*="icon"]');
return [...iconLinks].map(link => ({
rel: link.rel,
href: link.href,
type: link.type,
sizes: link.sizes.toString()
}));
}
// 9. Security Analysis
async analyzeSecurity() {
console.log('\n🔒 ANALYZING SECURITY');
console.log('=====================');
const security = {
https: location.protocol === 'https:',
csp: this.getCSP(),
mixedContent: this.checkMixedContent(),
externalResources: this.getExternalResources(),
cookies: this.analyzeCookies(),
localStorage: this.analyzeLocalStorage(),
sessionStorage: this.analyzeSessionStorage(),
permissions: this.checkPermissions()
};
console.log('HTTPS:', security.https);
console.log('CSP Enabled:', !!security.csp);
console.log('Mixed Content Issues:', security.mixedContent.length);
console.log('External Domains:', security.externalResources.domains.length);
this.results.analysis.security = security;
}
getCSP() {
const cspMeta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
return cspMeta ? cspMeta.content : null;
}
checkMixedContent() {
const issues = [];
if (location.protocol === 'https:') {
// Check for HTTP resources
const allResources = [
...document.querySelectorAll('img[src^="http:"]'),
...document.querySelectorAll('script[src^="http:"]'),
...document.querySelectorAll('link[href^="http:"]'),
...document.querySelectorAll('iframe[src^="http:"]')
];
allResources.forEach(resource => {
issues.push({
type: resource.tagName,
url: resource.src || resource.href,
id: resource.id,
classes: [...resource.classList]
});
});
}
return issues;
}
getExternalResources() {
const currentDomain = location.hostname;
const domains = new Set();
const resources = [];
// Check all resources with src/href attributes
const resourceElements = [
...document.querySelectorAll('[src]'),
...document.querySelectorAll('[href]')
];
resourceElements.forEach(element => {
const url = element.src || element.href;
try {
const urlObj = new URL(url);
if (urlObj.hostname !== currentDomain && urlObj.protocol.startsWith('http')) {
domains.add(urlObj.hostname);
resources.push({
type: element.tagName,
url,
domain: urlObj.hostname
});
}
} catch (e) {
// Invalid URL, skip
}
});
return {
domains: [...domains],
resources: resources.slice(0, 50) // Limit output
};
}
analyzeCookies() {
const cookies = document.cookie.split(';').filter(c => c.trim());
return {
count: cookies.length,
names: cookies.map(c => c.trim().split('=')[0]),
hasSecure: document.cookie.includes('Secure'),
hasHttpOnly: document.cookie.includes('HttpOnly'),
hasSameSite: document.cookie.includes('SameSite')
};
}
analyzeLocalStorage() {
try {
return {
available: true,
itemCount: localStorage.length,
keys: [...Array(localStorage.length)].map((_, i) => localStorage.key(i)),
estimatedSize: JSON.stringify(localStorage).length
};
} catch (e) {
return { available: false, error: e.message };
}
}
analyzeSessionStorage() {
try {
return {
available: true,
itemCount: sessionStorage.length,
keys: [...Array(sessionStorage.length)].map((_, i) => sessionStorage.key(i)),
estimatedSize: JSON.stringify(sessionStorage).length
};
} catch (e) {
return { available: false, error: e.message };
}
}
checkPermissions() {
const permissions = {};
// Check for common permission-requiring APIs
permissions.geolocation = 'geolocation' in navigator;
permissions.notifications = 'Notification' in window;
permissions.camera = 'mediaDevices' in navigator;
permissions.serviceWorker = 'serviceWorker' in navigator;
permissions.pushManager = 'PushManager' in window;
return permissions;
}
// 10. Performance Analysis
async analyzePerformance() {
console.log('\n⚡ ANALYZING PERFORMANCE');
console.log('========================');
const performance = {
timing: this.getPerformanceTiming(),
resources: this.getResourceTiming(),
vitals: await this.getWebVitals(),
memory: this.getMemoryInfo(),
observers: this.getPerformanceObservers()
};
console.log('Page Load Time:', performance.timing.loadComplete, 'ms');
console.log('DOM Content Loaded:', performance.timing.domContentLoaded, 'ms');
console.log('Resource Count:', performance.resources.length);
this.results.analysis.performance = performance;
}
getPerformanceTiming() {
const perfTiming = performance.timing;
const navigationStart = perfTiming.navigationStart;
return {
domLoading: perfTiming.domLoading - navigationStart,
domInteractive: perfTiming.domInteractive - navigationStart,
domContentLoaded: perfTiming.domContentLoadedEventEnd - navigationStart,
loadComplete: perfTiming.loadEventEnd - navigationStart,
firstPaint: this.getFirstPaint(),
firstContentfulPaint: this.getFirstContentfulPaint()
};
}
getFirstPaint() {
const paintEntries = performance.getEntriesByType('paint');
const firstPaint = paintEntries.find(entry => entry.name === 'first-paint');
return firstPaint ? firstPaint.startTime : null;
}
getFirstContentfulPaint() {
const paintEntries = performance.getEntriesByType('paint');
const firstContentfulPaint = paintEntries.find(entry => entry.name === 'first-contentful-paint');
return firstContentfulPaint ? firstContentfulPaint.startTime : null;
}
getResourceTiming() {
const resources = performance.getEntriesByType('resource');
return resources.map(resource => ({
name: resource.name,
type: this.getResourceType(resource.name),
duration: resource.duration,
size: resource.transferSize,
cached: resource.transferSize === 0 && resource.decodedBodySize > 0
})).slice(0, 30); // Limit output
}
getResourceType(url) {
if (url.includes('.css')) return 'stylesheet';
if (url.includes('.js')) return 'script';
if (url.match(/\.(jpg|jpeg|png|gif|webp|svg)$/)) return 'image';
if (url.includes('.woff') || url.includes('.ttf')) return 'font';
return 'other';
}
async getWebVitals() {
// Simplified web vitals - in a real implementation, you'd use the web-vitals library
return {
note: 'Use web-vitals library for accurate measurements',
cls: 'Not measured',
fid: 'Not measured',
lcp: 'Not measured'
};
}
getMemoryInfo() {
if ('memory' in performance) {
return {
usedJSHeapSize: performance.memory.usedJSHeapSize,
totalJSHeapSize: performance.memory.totalJSHeapSize,
jsHeapSizeLimit: performance.memory.jsHeapSizeLimit
};
}
return { available: false };
}
getPerformanceObservers() {
const observers = [];
// Check if PerformanceObserver is supported
if ('PerformanceObserver' in window) {
observers.push('PerformanceObserver supported');
// List supported entry types
if (PerformanceObserver.supportedEntryTypes) {
observers.push(...PerformanceObserver.supportedEntryTypes);