forked from KartikHalkunde/LockedIn-YT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
3028 lines (2666 loc) · 111 KB
/
content.js
File metadata and controls
3028 lines (2666 loc) · 111 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
// ===== CROSS-BROWSER COMPATIBILITY =====
// Support both Firefox (browser) and Chromium-based browsers (chrome)
if (typeof browser === 'undefined') {
var browser = chrome;
}
function normalizePathname(pathname) {
if (!pathname) return '/';
if (pathname.length > 1 && pathname.endsWith('/')) {
return pathname.replace(/\/+$/, '');
}
return pathname;
}
function isHomePath(pathname = window.location.pathname) {
const normalized = normalizePathname(pathname);
return normalized === '/' || normalized === '/home';
}
function isSubscriptionsPath(pathname = window.location.pathname) {
return normalizePathname(pathname) === '/feed/subscriptions';
}
function isHomeLikeSurface(pathname = window.location.pathname) {
const normalized = normalizePathname(pathname);
if (isHomePath(normalized) || isSubscriptionsPath(normalized)) {
return true;
}
return normalized === '/feed/trending';
}
// ===== INSTANT REDIRECT TO SUBSCRIPTIONS =====
// Check immediately on page load if we should redirect from homepage
(function instantRedirectCheck() {
if (isHomePath()) {
// Check storage synchronously using the sync API
browser.storage.sync.get(['hideFeed', 'redirectToSubs', 'extensionEnabled'], (result) => {
if (result.extensionEnabled !== false && result.hideFeed && result.redirectToSubs) {
// Redirect immediately before page renders
window.location.replace('https://www.youtube.com/feed/subscriptions');
}
});
}
})();
// ===== INSTANT HIDING WITH CSS =====
// Inject CSS to hide Shorts immediately, before JavaScript detection
const instantHideStyle = document.createElement('style');
instantHideStyle.id = 'lockedin-instant-hide';
// Initial content (will be updated dynamically)
instantHideStyle.textContent = '';
// Inject the style immediately (before anything loads)
(document.head || document.documentElement).appendChild(instantHideStyle);
// Instant CSS hiding for recommended videos
const instantRecsHideStyle = document.createElement('style');
instantRecsHideStyle.id = 'lockedin-instant-recs-hide';
instantRecsHideStyle.textContent = '';
(document.head || document.documentElement).appendChild(instantRecsHideStyle);
const navHideStyle = document.createElement('style');
navHideStyle.id = 'lockedin-nav-hide';
navHideStyle.textContent = `
html[data-lockedin-hide-home="true"] ytd-guide-entry-renderer:has(a[href="/"]),
html[data-lockedin-hide-home="true"] ytd-guide-entry-renderer:has(a[href="/home"]),
html[data-lockedin-hide-home="true"] ytd-guide-entry-renderer:has(a[title="Home"]),
html[data-lockedin-hide-home="true"] ytd-guide-entry-renderer:has(#endpoint[title="Home"]),
html[data-lockedin-hide-home="true"] ytd-mini-guide-entry-renderer:has(a[href="/"]),
html[data-lockedin-hide-home="true"] ytd-mini-guide-entry-renderer:has(a[href="/home"]),
html[data-lockedin-hide-home="true"] ytd-mini-guide-entry-renderer:has(a[title="Home"]),
html[data-lockedin-hide-home="true"] ytd-mini-guide-entry-renderer:has(#endpoint[title="Home"]),
html[data-lockedin-hide-home="true"] tp-yt-paper-tab:has(a[href="/"]),
html[data-lockedin-hide-home="true"] tp-yt-paper-tab:has(a[href^="/home"]),
html[data-lockedin-hide-home="true"] tp-yt-paper-tab:has(a[title="Home"]),
html[data-lockedin-hide-home="true"] yt-tab-shape:has(a[href="/"]),
html[data-lockedin-hide-home="true"] yt-tab-shape:has(a[href^="/home"]),
html[data-lockedin-hide-home="true"] yt-chip-cloud-chip-renderer:has(a[href="/"]),
html[data-lockedin-hide-home="true"] yt-chip-cloud-chip-renderer:has(a[href^="/home"]),
html[data-lockedin-hide-home="true"] yt-chip-cloud-chip-renderer:has(a[title="Home"]),
html[data-lockedin-hide-home="true"] ytm-pivot-bar-item-renderer:has([href="/"]),
html[data-lockedin-hide-home="true"] ytm-pivot-bar-item-renderer:has([href="/home"]) {
display: none !important;
}
html[data-lockedin-hide-shorts-tab="true"] ytd-guide-entry-renderer:has(a[href^="/shorts"]),
html[data-lockedin-hide-shorts-tab="true"] ytd-guide-entry-renderer:has(a[title="Shorts"]),
html[data-lockedin-hide-shorts-tab="true"] ytd-guide-entry-renderer:has(#endpoint[title="Shorts"]),
html[data-lockedin-hide-shorts-tab="true"] ytd-mini-guide-entry-renderer:has(a[href^="/shorts"]),
html[data-lockedin-hide-shorts-tab="true"] ytd-mini-guide-entry-renderer:has(a[title="Shorts"]),
html[data-lockedin-hide-shorts-tab="true"] ytd-mini-guide-entry-renderer:has(#endpoint[title="Shorts"]),
html[data-lockedin-hide-shorts-tab="true"] tp-yt-paper-tab:has(a[href^="/shorts"]),
html[data-lockedin-hide-shorts-tab="true"] tp-yt-paper-tab:has(a[title="Shorts"]),
html[data-lockedin-hide-shorts-tab="true"] yt-tab-shape:has(a[href^="/shorts"]),
html[data-lockedin-hide-shorts-tab="true"] yt-chip-cloud-chip-renderer:has(a[href^="/shorts"]),
html[data-lockedin-hide-shorts-tab="true"] yt-chip-cloud-chip-renderer:has(a[title="Shorts"]),
html[data-lockedin-hide-shorts-tab="true"] yt-chip-cloud-chip-renderer:has(div[title*="Shorts" i]),
html[data-lockedin-hide-shorts-tab="true"] ytm-pivot-bar-item-renderer:has([href^="/shorts"]),
html[data-lockedin-hide-shorts-tab="true"] ytm-pivot-bar-item-renderer:has([data-pivot-id="shorts"]) {
display: none !important;
}
`;
(document.head || document.documentElement).appendChild(navHideStyle);
// ===== LOCALIZATION (CONTENT SCRIPT) =====
const SUPPORTED_LANGUAGES = ['en', 'es', 'hi', 'pt', 'fr', 'de'];
const FALLBACK_LANGUAGE = 'en';
const I18N_STRINGS = {
en: {
'placeholder.alt': 'Stay Focused!'
},
es: {
'placeholder.alt': '¡Concéntrate!'
},
hi: {
'placeholder.alt': 'ध्यान केंद्रित रखें!'
},
pt: {
'placeholder.alt': 'Mantenha o foco!'
},
fr: {
'placeholder.alt': 'Reste concentré !'
},
de: {
'placeholder.alt': 'Bleib fokussiert!'
}
};
let activeLanguage = FALLBACK_LANGUAGE;
function formatTemplate(template, replacements) {
if (!template || !replacements) return template;
return Object.keys(replacements).reduce((result, key) => {
const value = replacements[key];
return result.replace(new RegExp(`{${key}}`, 'g'), value);
}, template);
}
function getBrowserLanguage() {
try {
if (browser && browser.i18n && typeof browser.i18n.getUILanguage === 'function') {
return browser.i18n.getUILanguage();
}
} catch (error) {
console.debug('LockedIn: Unable to detect browser language', error);
}
if (typeof navigator !== 'undefined' && navigator.language) {
return navigator.language;
}
return FALLBACK_LANGUAGE;
}
function resolveLanguagePreference(preferred) {
if (preferred && preferred !== 'auto' && SUPPORTED_LANGUAGES.includes(preferred)) {
return preferred;
}
const browserLang = (getBrowserLanguage() || '').toLowerCase();
const exactMatch = SUPPORTED_LANGUAGES.find((code) => browserLang === code);
if (exactMatch) {
return exactMatch;
}
const partialMatch = SUPPORTED_LANGUAGES.find((code) => browserLang.startsWith(`${code}-`));
return partialMatch || FALLBACK_LANGUAGE;
}
function setActiveLanguage(languageCode) {
activeLanguage = SUPPORTED_LANGUAGES.includes(languageCode) ? languageCode : FALLBACK_LANGUAGE;
}
function translate(key, replacements = null, languageCode = activeLanguage) {
if (!key) {
return '';
}
const languagePack = I18N_STRINGS[languageCode] || I18N_STRINGS[FALLBACK_LANGUAGE] || {};
let template = languagePack[key];
if (template === undefined) {
const fallbackPack = I18N_STRINGS[FALLBACK_LANGUAGE] || {};
template = fallbackPack[key] || '';
}
if (!template) {
return '';
}
return replacements ? formatTemplate(template, replacements) : template;
}
async function initLocalization() {
try {
const stored = await browser.storage.sync.get('language');
const preferred = stored.language || 'auto';
setActiveLanguage(resolveLanguagePreference(preferred));
} catch (error) {
console.debug('LockedIn: Unable to initialize localization', error);
setActiveLanguage(FALLBACK_LANGUAGE);
}
}
function handleLanguagePreferenceChange(preferred) {
setActiveLanguage(resolveLanguagePreference(preferred || 'auto'));
}
initLocalization();
// Function to enable/disable instant CSS hiding
function setInstantHiding(hideHomepage, hideSearch, hideGlobally = false) {
const style = document.getElementById('lockedin-instant-hide');
if (!style) return;
let css = '';
const navShortsCss = `
/* Hide Shorts tab across top navigation surfaces */
tp-yt-paper-tab:has(a[href^="/shorts"]),
tp-yt-paper-tab:has(a[title="Shorts"]),
tp-yt-paper-tab:has(div[title*="Shorts" i]),
yt-tab-shape:has(a[href^="/shorts"]),
yt-tab-shape:has(a[title="Shorts"]),
yt-chip-cloud-chip-renderer:has(a[href^="/shorts"]),
yt-chip-cloud-chip-renderer:has(a[title="Shorts"]),
yt-chip-cloud-chip-renderer:has(div[title*="Shorts" i]),
ytd-feed-filter-chip-bar-renderer tp-yt-paper-tab:has(a[href^="/shorts"]),
ytd-feed-filter-chip-bar-renderer yt-chip-cloud-chip-renderer:has(a[href^="/shorts"]),
ytm-pivot-bar-item-renderer:has([href^="/shorts"]),
ytm-pivot-bar-item-renderer:has([data-pivot-id="shorts"]) {
display: none !important;
}
`;
// Global Shorts hiding takes precedence - hides Shorts EVERYWHERE
if (hideGlobally) {
css = `
/* ===== GLOBAL SHORTS HIDING ===== */
/* Hide Shorts tab in sidebar (expanded and collapsed) */
ytd-guide-entry-renderer:has(a[href="/shorts"]),
ytd-mini-guide-entry-renderer:has(a[href="/shorts"]),
ytd-guide-entry-renderer:has(a[title="Shorts"]),
ytd-mini-guide-entry-renderer:has(a[title="Shorts"]) {
display: none !important;
}
/* Hide Shorts shelf containers everywhere */
ytd-reel-shelf-renderer,
ytd-rich-shelf-renderer:has([href^="/shorts/"]),
ytd-rich-section-renderer:has([href^="/shorts/"]),
grid-shelf-view-model:has([href^="/shorts/"]) {
display: none !important;
}
/* Hide all video renderers that link to Shorts */
ytd-rich-item-renderer:has([href^="/shorts/"]),
ytd-video-renderer:has([href^="/shorts/"]),
ytd-grid-video-renderer:has([href^="/shorts/"]),
ytd-compact-video-renderer:has([href^="/shorts/"]),
ytd-reel-item-renderer {
display: none !important;
}
/* Hide Shorts by overlay badge */
ytd-rich-item-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]),
ytd-video-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]),
ytd-grid-video-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]),
ytd-compact-video-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]) {
display: none !important;
}
/* Hide Shorts in sidebar recommendations (watch page) */
#secondary ytd-compact-video-renderer:has([href^="/shorts/"]),
#related ytd-compact-video-renderer:has([href^="/shorts/"]) {
display: none !important;
}
/* Hide Shorts filter chips on search page */
yt-chip-cloud-chip-renderer:has([title*="Short" i]),
yt-chip-cloud-chip-renderer:has([aria-label*="Short" i]) {
display: none !important;
}
/* Mobile: Hide Shorts elements */
ytm-reel-shelf-renderer,
ytm-shorts-lockup-view-model,
ytm-shorts-lockup-view-model-v2,
ytm-pivot-bar-item-renderer:has([href="/shorts"]),
ytm-pivot-bar-item-renderer:has([data-pivot-id="shorts"]) {
display: none !important;
}
`;
css += navShortsCss;
} else {
// Add homepage-specific CSS if hideHomepage is enabled
if (hideHomepage) {
css += `
/* Hide Shorts shelf containers on homepage */
ytd-reel-shelf-renderer:not([data-lockedin-hidden]),
ytd-rich-shelf-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
ytd-rich-section-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]) {
display: none;
}
/* Hide video renderers that link to Shorts on homepage */
ytd-rich-item-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
ytd-reel-item-renderer:not([data-lockedin-hidden]) {
display: none;
}
/* Hide Shorts tab in sidebar */
ytd-guide-entry-renderer:has(a[href="/shorts"]):not([data-lockedin-hidden]),
ytd-mini-guide-entry-renderer:has(a[href="/shorts"]):not([data-lockedin-hidden]) {
display: none;
}
/* Hide Shorts overlay badge items on homepage */
ytd-rich-item-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]):not([data-lockedin-hidden]) {
display: none;
}
`;
css += navShortsCss;
}
// Add search-specific CSS if hideSearch is enabled
if (hideSearch) {
css += `
/* Hide Shorts shelf containers on search page ONLY */
ytd-search ytd-reel-shelf-renderer:not([data-lockedin-hidden]),
ytd-search ytd-rich-shelf-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
ytd-search ytd-rich-section-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
ytd-search grid-shelf-view-model:not([data-lockedin-hidden]),
[page-subtype="search"] ytd-reel-shelf-renderer:not([data-lockedin-hidden]),
[page-subtype="search"] ytd-rich-shelf-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
[page-subtype="search"] ytd-rich-section-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
[page-subtype="search"] grid-shelf-view-model:not([data-lockedin-hidden]) {
display: none;
}
/* Hide video renderers that link to Shorts on search page ONLY */
ytd-search ytd-video-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]),
[page-subtype="search"] ytd-video-renderer:has([href^="/shorts/"]):not([data-lockedin-hidden]) {
display: none;
}
/* Hide Shorts overlay badge items on search page ONLY */
ytd-search ytd-video-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]):not([data-lockedin-hidden]),
[page-subtype="search"] ytd-video-renderer:has(ytd-thumbnail-overlay-time-status-renderer[overlay-style="SHORTS"]):not([data-lockedin-hidden]) {
display: none;
}
`;
}
}
// Update the style element
style.textContent = css;
}
// Function to set instant CSS hiding for recommended videos
function setInstantRecsHiding(hideRecommended, hideSidebar) {
const style = document.getElementById('lockedin-instant-recs-hide');
if (!style) return;
let css = '';
// Only apply instant hiding if either hideRecommended or hideSidebar is enabled
if (hideRecommended || hideSidebar) {
css = `
/* ===== INSTANT RECOMMENDED VIDEOS HIDING ===== */
/* Hide chip cloud (sidebar only) */
#secondary yt-chip-cloud-renderer,
#secondary yt-related-chip-cloud-renderer {
display: none !important;
}
/* Hide video renderers in sidebar only */
#secondary ytd-compact-video-renderer:not([data-lockedin-hidden]),
#secondary ytd-compact-movie-renderer:not([data-lockedin-hidden]),
#secondary ytd-compact-radio-renderer:not([data-lockedin-hidden]),
#secondary ytd-compact-autoplay-renderer:not([data-lockedin-hidden]),
#secondary ytd-reel-item-renderer:not([data-lockedin-hidden]),
#secondary ytd-video-renderer:not([data-lockedin-hidden]) {
display: none !important;
}
/* Hide recommendation containers that don't host transcript/engagement panels */
#secondary ytd-item-section-renderer:not([data-lockedin-hidden]):not(:has(ytd-engagement-panel-section-list-renderer)):not(:has(ytd-transcript-segment-list-renderer)),
#secondary ytd-continuation-item-renderer:not([data-lockedin-hidden]):not(:has(ytd-engagement-panel-section-list-renderer)):not(:has(ytd-transcript-segment-list-renderer)),
#secondary ytd-watch-next-secondary-results-renderer:not([data-lockedin-hidden]):not(:has(ytd-engagement-panel-section-list-renderer)):not(:has(ytd-transcript-segment-list-renderer)),
#secondary #related:not([data-lockedin-hidden]):not(:has(ytd-engagement-panel-section-list-renderer)):not(:has(ytd-transcript-segment-list-renderer)) {
visibility: hidden !important;
pointer-events: none !important;
min-height: 0 !important;
max-height: 0 !important;
overflow: hidden !important;
}
/* If a container hosts transcript/engagement panels, keep it visible */
#secondary ytd-item-section-renderer:has(ytd-engagement-panel-section-list-renderer),
#secondary ytd-item-section-renderer:has(ytd-transcript-segment-list-renderer),
#secondary ytd-continuation-item-renderer:has(ytd-engagement-panel-section-list-renderer),
#secondary ytd-continuation-item-renderer:has(ytd-transcript-segment-list-renderer),
#secondary ytd-watch-next-secondary-results-renderer:has(ytd-engagement-panel-section-list-renderer),
#secondary ytd-watch-next-secondary-results-renderer:has(ytd-transcript-segment-list-renderer),
#secondary #related:has(ytd-engagement-panel-section-list-renderer),
#secondary #related:has(ytd-transcript-segment-list-renderer) {
visibility: visible !important;
pointer-events: auto !important;
min-height: auto !important;
max-height: none !important;
overflow: visible !important;
}
`;
}
style.textContent = css;
}
function setRootFlag(flag, enabled) {
const root = document.documentElement;
if (!root) return;
if (enabled) {
root.setAttribute(flag, 'true');
} else {
root.removeAttribute(flag);
}
}
// ===== DEBOUNCE UTILITY =====
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// ===== DEFAULT SETTINGS =====
const DEFAULT_SETTINGS = {
hideFeed: false,
redirectToSubs: false,
hideShortsHomepage: false,
hideCommunityPosts: false,
hideShortsGlobally: false,
redirectShorts: false,
hideSidebar: false,
hideRecommended: false,
hideSidebarShorts: false,
hideLiveChat: false,
hideEndCards: false,
hideComments: false,
disableAutoplay: false,
hideSearchRecommended: false,
hideShortsSearch: false,
hideExplore: false,
hideMoreFromYT: false,
hidePlaylists: false,
hideSubscriptions: false,
extensionEnabled: true
};
let latestSyncedSettings = { ...DEFAULT_SETTINGS };
let sidebarObserver = null;
let secondaryObserver = null;
let sidebarHideRetryTimers = [];
const GUIDE_HIDE_ATTR = 'data-lockedin-guide';
const GUIDE_HOME_SELECTORS = [
'ytd-guide-entry-renderer a[href="/"]',
'ytd-guide-entry-renderer a[href="/home"]',
'ytd-guide-entry-renderer a[title="Home"]',
'ytd-guide-entry-renderer #endpoint[title="Home"]',
'ytd-mini-guide-entry-renderer a[href="/"]',
'ytd-mini-guide-entry-renderer a[href="/home"]',
'ytd-mini-guide-entry-renderer a[title="Home"]',
'ytd-mini-guide-entry-renderer #endpoint[title="Home"]'
];
const GUIDE_SHORTS_SELECTORS = [
'ytd-guide-entry-renderer a[href^="/shorts"]',
'ytd-guide-entry-renderer a[title="Shorts"]',
'ytd-guide-entry-renderer #endpoint[title="Shorts"]',
'ytd-mini-guide-entry-renderer a[href^="/shorts"]',
'ytd-mini-guide-entry-renderer a[title="Shorts"]',
'ytd-mini-guide-entry-renderer #endpoint[title="Shorts"]'
];
const guideObserver = new MutationObserver(() => {
if (latestSyncedSettings.extensionEnabled === false) return;
updateGuideVisibility();
// Re-apply Explore and More From YT hiding when sidebar content changes
hideExplore(latestSyncedSettings.hideExplore);
hideMoreFromYT(latestSyncedSettings.hideMoreFromYT);
});
function applyInstantShortsCssFromCache() {
setInstantHiding(
latestSyncedSettings.hideShortsHomepage,
latestSyncedSettings.hideShortsSearch,
latestSyncedSettings.hideShortsGlobally
);
}
function applyInstantRecsCssFromCache() {
setInstantRecsHiding(
latestSyncedSettings.hideRecommended,
latestSyncedSettings.hideSidebar
);
}
function applyRedirectStateFromCache() {
const shouldRedirect =
latestSyncedSettings.hideFeed && latestSyncedSettings.redirectToSubs;
redirectToSubscriptions(shouldRedirect);
}
function ensureSidebarObserver(active) {
if (!active) {
if (sidebarObserver) {
sidebarObserver.disconnect();
sidebarObserver = null;
}
if (secondaryObserver) {
secondaryObserver.disconnect();
secondaryObserver = null;
}
sidebarHideRetryTimers.forEach(clearTimeout);
sidebarHideRetryTimers = [];
return;
}
if (sidebarObserver) return;
const sidebarCallback = debounce(() => {
if (latestSyncedSettings.extensionEnabled === false) return;
if (latestSyncedSettings.hideSidebar) {
hideAll(true);
} else if (latestSyncedSettings.hideRecommended) {
hideRecommendedVideos(true);
hideSidebarShorts(latestSyncedSettings.hideSidebarShorts);
}
ensureTranscriptPanelVisible();
}, 80);
sidebarObserver = new MutationObserver(sidebarCallback);
sidebarObserver.observe(document.body, { childList: true, subtree: true });
sidebarCallback();
// Targeted observer for #secondary so new recs added after refresh are hidden immediately
const attachSecondaryObserver = () => {
const secondary = document.querySelector('#secondary');
if (!secondary) return false;
const secondaryCallback = debounce(() => {
if (latestSyncedSettings.extensionEnabled === false) return;
if (latestSyncedSettings.hideSidebar) {
hideAll(true);
} else if (latestSyncedSettings.hideRecommended) {
hideRecommendedVideos(true);
hideSidebarShorts(latestSyncedSettings.hideSidebarShorts);
}
ensureTranscriptPanelVisible();
}, 50);
secondaryObserver = new MutationObserver(secondaryCallback);
secondaryObserver.observe(secondary, { childList: true, subtree: true });
secondaryCallback();
return true;
};
// Try immediately; if not present yet, retry shortly
if (!attachSecondaryObserver()) {
setTimeout(attachSecondaryObserver, 300);
setTimeout(attachSecondaryObserver, 900);
}
}
function scheduleSidebarHideRetries(settings) {
sidebarHideRetryTimers.forEach(clearTimeout);
sidebarHideRetryTimers = [];
if (settings.hideSidebar || settings.hideRecommended) {
const actions = () => {
if (settings.hideSidebar) {
hideAll(true);
} else if (settings.hideRecommended) {
hideRecommendedVideos(true);
hideSidebarShorts(settings.hideSidebarShorts);
}
ensureTranscriptPanelVisible();
};
[250, 800, 1800, 3200].forEach((ms) => {
sidebarHideRetryTimers.push(setTimeout(actions, ms));
});
}
}
function toggleGuideSelectors(selectors, marker, shouldHide) {
if (!selectors || selectors.length === 0) return;
const combinedSelector = selectors.join(',');
document.querySelectorAll(combinedSelector).forEach((link) => {
const container = link.closest('ytd-guide-entry-renderer, ytd-mini-guide-entry-renderer');
if (!container) return;
if (shouldHide) {
container.style.display = 'none';
container.setAttribute('hidden', '');
container.setAttribute(GUIDE_HIDE_ATTR, marker);
} else if (container.getAttribute(GUIDE_HIDE_ATTR) === marker) {
container.style.display = '';
container.removeAttribute('hidden');
container.removeAttribute(GUIDE_HIDE_ATTR);
}
});
}
function updateGuideVisibility() {
const enabled = latestSyncedSettings.extensionEnabled !== false;
const hideHomeTab = enabled && (
latestSyncedSettings.hideFeed ||
latestSyncedSettings.redirectToSubs
);
const hideShortsTab = enabled && (
latestSyncedSettings.hideShortsHomepage ||
latestSyncedSettings.hideShortsGlobally ||
latestSyncedSettings.hideShortsSearch ||
latestSyncedSettings.redirectShorts
);
setRootFlag('data-lockedin-hide-home', hideHomeTab);
setRootFlag('data-lockedin-hide-shorts-tab', hideShortsTab);
toggleGuideSelectors(GUIDE_HOME_SELECTORS, 'home', hideHomeTab);
toggleGuideSelectors(GUIDE_SHORTS_SELECTORS, 'shorts', hideShortsTab);
}
function observeGuideContainers() {
document.querySelectorAll('ytd-guide-renderer, ytd-mini-guide-renderer').forEach((container) => {
guideObserver.observe(container, { childList: true, subtree: true });
});
}
// ===== STATS TRACKING =====
const DEFAULT_STATS = {
shortsBlocked: 0,
recsHidden: 0,
endCardsBlocked: 0,
autoplayStops: 0,
sessionTimeMs: 0,
todaySessionMs: 0,
todayDate: null,
weekTimeSaved: 0,
weekStartDate: null,
firstUseDate: null
};
// Time saved estimates (in minutes)
const TIME_SAVED_ESTIMATES = {
short: 0.5,
recommendation: 5,
endCard: 3,
autoplay: 8
};
// Track session time
let sessionStartTime = null;
let lastActiveTime = null;
let isTracking = false;
let isPageActive = true;
// Check if page is currently active (visible and focused)
function isPageCurrentlyActive() {
return document.visibilityState === 'visible' && document.hasFocus();
}
// Initialize session tracking
function initSessionTracking() {
if (isTracking) return;
isTracking = true;
sessionStartTime = Date.now();
lastActiveTime = Date.now();
isPageActive = isPageCurrentlyActive();
// Update session time every 30 seconds
setInterval(updateSessionTime, 30000);
// Track visibility changes
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
lastActiveTime = Date.now();
isPageActive = document.hasFocus();
} else {
isPageActive = false;
updateSessionTime();
}
});
// Track focus changes
window.addEventListener('focus', () => {
lastActiveTime = Date.now();
isPageActive = true;
});
window.addEventListener('blur', () => {
isPageActive = false;
updateSessionTime();
});
}
function updateSessionTime() {
if (!lastActiveTime || !isPageCurrentlyActive()) return;
const now = Date.now();
const elapsed = now - lastActiveTime;
lastActiveTime = now;
// Only count if less than 5 minutes (user might have been away)
if (elapsed < 5 * 60 * 1000) {
browser.storage.local.get('stats').then((result) => {
const stats = { ...DEFAULT_STATS, ...result.stats };
const today = new Date().toDateString();
// Reset today's time if it's a new day
if (stats.todayDate !== today) {
stats.todaySessionMs = 0;
stats.todayDate = today;
}
stats.sessionTimeMs += elapsed;
stats.todaySessionMs += elapsed;
browser.storage.local.set({ stats });
}).catch(() => {});
}
}
// Track stats for blocked elements - only when page is active
function trackStat(type, count = 1) {
if (count <= 0) return;
// Only track stats when user is actively on the YouTube page
if (!isPageCurrentlyActive()) return;
browser.storage.local.get('stats').then((result) => {
const stats = { ...DEFAULT_STATS, ...result.stats };
const today = new Date().toDateString();
const now = Date.now();
// Initialize first use date
if (!stats.firstUseDate) {
stats.firstUseDate = now;
}
// Reset today's time if it's a new day
if (stats.todayDate !== today) {
stats.todaySessionMs = 0;
stats.todayDate = today;
}
// Reset weekly stats if it's a new week (Sunday)
const currentWeekStart = getWeekStart(now);
if (!stats.weekStartDate || stats.weekStartDate !== currentWeekStart) {
stats.weekTimeSaved = 0;
stats.weekStartDate = currentWeekStart;
}
// Update specific stat
switch (type) {
case 'shorts':
stats.shortsBlocked += count;
stats.weekTimeSaved += count * TIME_SAVED_ESTIMATES.short;
break;
case 'recs':
stats.recsHidden += count;
stats.weekTimeSaved += count * TIME_SAVED_ESTIMATES.recommendation;
break;
case 'endcards':
stats.endCardsBlocked += count;
stats.weekTimeSaved += count * TIME_SAVED_ESTIMATES.endCard;
break;
case 'autoplay':
stats.autoplayStops += count;
stats.weekTimeSaved += count * TIME_SAVED_ESTIMATES.autoplay;
break;
}
browser.storage.local.set({ stats });
}).catch(() => {});
}
function getWeekStart(timestamp) {
const date = new Date(timestamp);
const day = date.getDay();
const diff = date.getDate() - day;
const weekStart = new Date(date.setDate(diff));
return weekStart.toDateString();
}
// Start session tracking when script loads
initSessionTracking();
// ===== INITIALIZE SETTINGS ON INSTALL =====
// This fixes the race condition - ensures settings exist before content script runs
browser.storage.sync.get(null).then((settings) => {
// If no settings exist, initialize with defaults
if (Object.keys(settings).length === 0) {
latestSyncedSettings = { ...DEFAULT_SETTINGS };
browser.storage.sync.set(DEFAULT_SETTINGS).catch((error) => {
console.error('LockedIn: Failed to initialize settings', error);
});
} else {
latestSyncedSettings = { ...DEFAULT_SETTINGS, ...settings };
}
updateGuideVisibility();
}).catch((error) => {
console.error('LockedIn: Failed to check settings', error);
});
// ===== HELPER FUNCTIONS =====
function toggleElement(selector, shouldHide) {
const element = document.querySelector(selector);
if (element) {
element.style.display = shouldHide ? 'none' : '';
}
}
function toggleAllElements(selector, shouldHide) {
document.querySelectorAll(selector).forEach(el => {
el.style.display = shouldHide ? 'none' : '';
});
}
function dataUrlToBlob(dataUrl) {
const parts = dataUrl.split(',');
if (parts.length < 2) {
throw new Error('Invalid data URL');
}
const mimeMatch = parts[0].match(/:(.*?);/);
const mime = mimeMatch ? mimeMatch[1] : 'image/png';
const binaryString = atob(parts[1]);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return new Blob([bytes], { type: mime });
}
function getImageSource(imageUrl) {
if (!imageUrl || !imageUrl.startsWith('data:')) {
return { src: imageUrl, cleanup: null };
}
try {
const blob = dataUrlToBlob(imageUrl);
const objectUrl = URL.createObjectURL(blob);
return {
src: objectUrl,
cleanup: () => URL.revokeObjectURL(objectUrl)
};
} catch (error) {
console.error('LockedIn: Failed to convert custom meme to blob', error);
return { src: null, cleanup: null };
}
}
// ===== REDIRECT TO SUBSCRIPTIONS PAGE =====
let homepageInterceptorSetup = false;
function redirectToSubscriptions(shouldRedirect) {
const styleId = 'lockedin-hide-homepage-nav';
if (!shouldRedirect) {
// Remove the CSS that hides homepage navigation
const existingStyle = document.getElementById(styleId);
if (existingStyle) existingStyle.remove();
// Remove click interceptor
if (window._lockedinHomepageInterceptor) {
document.removeEventListener('click', window._lockedinHomepageInterceptor, true);
window._lockedinHomepageInterceptor = null;
}
homepageInterceptorSetup = false;
return;
}
// Inject CSS to hide homepage from sidebar and top navigation
if (!document.getElementById(styleId)) {
const style = document.createElement('style');
style.id = styleId;
style.textContent = `
/* Hide Home tab in sidebar (expanded) */
ytd-guide-entry-renderer:has(a[href="/"]),
ytd-guide-entry-renderer:has(a[title="Home"]) {
display: none !important;
}
/* Hide Home tab in mini sidebar (collapsed) */
ytd-mini-guide-entry-renderer:has(a[href="/"]),
ytd-mini-guide-entry-renderer:has(a[title="Home"]) {
display: none !important;
}
/* Hide Home tab in top navigation chips and tabs */
tp-yt-paper-tab:has(a[href="/"]),
tp-yt-paper-tab:has(a[href^="/home"]),
tp-yt-paper-tab:has(a[title="Home"]),
tp-yt-paper-tab:has(div[title="Home"]),
yt-tab-shape:has(a[href="/"]),
yt-tab-shape:has(a[href^="/home"]),
yt-chip-cloud-chip-renderer:has(a[href="/"]),
yt-chip-cloud-chip-renderer:has(a[href^="/home"]),
yt-chip-cloud-chip-renderer:has(div[title="Home"]),
ytd-feed-filter-chip-bar-renderer tp-yt-paper-tab:has(a[href="/"]),
ytd-feed-filter-chip-bar-renderer yt-chip-cloud-chip-renderer:has(a[href="/"]),
ytm-pivot-bar-item-renderer:has([href="/"])
{
display: none !important;
}
`;
(document.head || document.documentElement).appendChild(style);
}
// Intercept clicks on YouTube logo and any homepage links
if (!homepageInterceptorSetup) {
window._lockedinHomepageInterceptor = function(e) {
const target = e.target.closest('a[href="/"], a[href="/home"], #logo, ytd-logo, #start a, a[title="YouTube Home"]');
if (target) {
e.preventDefault();
e.stopPropagation();
window.location.href = 'https://www.youtube.com/feed/subscriptions';
}
};
document.addEventListener('click', window._lockedinHomepageInterceptor, true);
homepageInterceptorSetup = true;
}
// If currently on homepage, redirect immediately
if (isHomePath()) {
window.location.replace('https://www.youtube.com/feed/subscriptions');
}
}
function hideFeed(shouldHide) {
const placeholderId = 'lockedin-feed-placeholder';
if (!shouldHide) {
// Restore feed elements
const feedElements = [
document.querySelector('ytd-rich-grid-renderer'),
document.querySelector('ytd-two-column-browse-results-renderer'),
...document.querySelectorAll('[data-lockedin-hidden="feed"]')
].filter(el => el);
feedElements.forEach(el => {
el.style.removeProperty('display');
el.removeAttribute('data-lockedin-hidden');
});
// Remove placeholder if it exists
const placeholder = document.getElementById(placeholderId);
if (placeholder) {
placeholder.remove();
}
return;
}
// Only hide on homepage
if (window.location.pathname === '/' || window.location.pathname === '/home') {
// Hide multiple feed-related elements
const feedSelectors = [
'ytd-rich-grid-renderer',
'ytd-two-column-browse-results-renderer #primary',
'ytd-browse[page-subtype="home"]'
];
feedSelectors.forEach(selector => {
const elements = document.querySelectorAll(selector);
elements.forEach(el => {
if (!el.hasAttribute('data-lockedin-hidden')) {
el.style.setProperty('display', 'none', 'important');
el.setAttribute('data-lockedin-hidden', 'feed');
}
});
});
// Create and inject placeholder with random meme image
if (!document.getElementById(placeholderId)) {
const placeholder = document.createElement('div');
placeholder.id = placeholderId;
placeholder.style.cssText = `
position: absolute;
top: 200px;
left: 50%;
transform: translateX(-50%);
text-align: center;
z-index: 1;
pointer-events: none;
`;
// Check for custom memes first
browser.storage.local.get('customMemes', (result) => {
let imageUrl;
if (result.customMemes && result.customMemes.length > 0) {
// Use random custom meme
imageUrl = result.customMemes[Math.floor(Math.random() * result.customMemes.length)];
console.log('LockedIn: Using custom meme');
} else {
// Use default meme image
imageUrl = browser.runtime.getURL('homepage/meme1.jpg');