Repository navigation
Expand file tree
/
Copy pathcontent-listing.js
More file actions
1487 lines (1289 loc) · 51.8 KB
/
Copy pathcontent-listing.js
File metadata and controls
1487 lines (1289 loc) · 51.8 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
// ==== GARANTE VARIÁVEIS GLOBAIS NO TOPO ====
(() => {
'use strict';
const jumpKeyGlobalState = window.__jumpKeyGlobalState || (window.__jumpKeyGlobalState = {
initialized: false,
keydownHandler: null,
storageHandler: null,
popstateHandler: null,
hashchangeHandler: null,
pagehideHandler: null,
ytNavigationHandler: null,
resizeHandler: null,
fullscreenchangeHandler: null,
DOMContentLoadedHandler: null,
loadHandler: null,
cssObserver: null,
videoObserver: null
});
let listingLastAppliedExpandedAt = 0;
let listingShortsModeActive = false;
let listingLongVideoModeActive = false;
let listingFullscreenExitValidation = null;
let listingCustomStyle = null;
let listingLongVideoStyle = null;
let listingObservedRootNode = null;
let pendingShortsModeReapplyTimeout = null;
let listingApplyInProgress = false;
// ...existing code...
const WATCH_LOC_SELECTORS = [
'ytd-rich-item-renderer',
'ytd-playlist-video-renderer',
'ytd-notification-renderer',
'ytd-search ytd-video-renderer',
'.ytp-endscreen-content .ytp-videowall-still',
'.ytp-fullscreen-grid .ytp-modern-videowall-still',
'ytd-watch-metadata #top-level-buttons-computed'
].join(', ');
function parseDurationTextSync(durationText) {
if (!durationText || typeof durationText !== 'string') return null;
const cleaned = durationText.trim();
if (!cleaned) return null;
const parts = cleaned.split(':').map(p => Number(p.replace(/[^0-9]/g, '')));
if (parts.some(p => Number.isNaN(p))) return null;
let seconds = 0;
if (parts.length === 3) seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
else if (parts.length === 2) seconds = parts[0] * 60 + parts[1];
else if (parts.length === 1) seconds = parts[0];
return Number.isFinite(seconds) && seconds > 0 ? seconds : null;
}
function getTextSync(value) {
if (!value) return '';
if (typeof value === 'string') return value;
if (typeof value.simpleText === 'string') return value.simpleText;
if (Array.isArray(value.runs)) return value.runs.map(run => run?.text || '').join('').trim();
return '';
}
async function extractPlaylistVideosForSync() {
const videos = [];
const seen = new Set();
const addVideo = (videoId, title, durationSec) => {
if (!videoId || seen.has(videoId)) return;
seen.add(videoId);
videos.push({
videoId,
title: title || 'Unknown',
duration: Number.isFinite(Number(durationSec)) && durationSec > 0 ? Number(durationSec) : null
});
};
try {
const scripts = document.querySelectorAll('script');
for (const script of scripts) {
const text = script.textContent || '';
if (!text.includes('ytInitialData')) continue;
const regexes = [
/var ytInitialData\s*=\s*({[\s\S]*?});/,
/window\[\"ytInitialData\"\]\s*=\s*({[\s\S]*?});/
];
for (const regex of regexes) {
const match = text.match(regex);
if (!match || !match[1]) continue;
let data = null;
try { data = JSON.parse(match[1]); } catch (e) { continue; }
const contents = data?.contents?.twoColumnBrowseResultsRenderer?.tabs;
if (!Array.isArray(contents)) continue;
for (const tab of contents) {
const sectionContents = tab?.tabRenderer?.content?.sectionListRenderer?.contents || [];
for (const section of sectionContents) {
const items = section?.itemSectionRenderer?.contents || [];
for (const item of items) {
const listItems = item?.playlistVideoListRenderer?.contents || [];
for (const entry of listItems) {
const renderer = entry?.playlistVideoRenderer;
const durationText = renderer?.lengthText?.simpleText || (renderer?.lengthText?.runs ? renderer.lengthText.runs.map(r => r.text).join('').trim() : '');
const parsedDuration = parseDurationTextSync(durationText);
const videoId = renderer?.videoId;
const title = getTextSync(renderer?.title);
addVideo(videoId, title, parsedDuration);
}
}
}
}
}
}
if (videos.length === 0) {
const videoElements = document.querySelectorAll('ytd-playlist-video-renderer');
for (const el of videoElements) {
const link = el.querySelector('a#video-title');
if (!link || !link.href) continue;
const match = link.href.match(/[?&]v=([^&]+)/);
const shortsMatch = link.href.match(/\/shorts\/([^/?&]+)/);
const videoId = (match && match[1]) ? match[1] : (shortsMatch && shortsMatch[1]) ? shortsMatch[1] : null;
if (videoId) {
const durationElem = el.querySelector('ytd-thumbnail-overlay-time-status-renderer span') || el.querySelector('span.ytd-thumbnail-overlay-time-status-renderer');
const durationText = durationElem ? (durationElem.textContent || '').trim() : '';
const parsedDuration = parseDurationTextSync(durationText);
const title = (link.textContent || '').trim();
addVideo(videoId, title, parsedDuration);
}
}
}
if (videos.length > 0) {
return { success: true, videos, method: 'content-listing-extract' };
}
return { success: false, error: 'No videos found in playlist' };
} catch (err) {
return { success: false, error: err && err.message ? err.message : String(err) };
}
}
async function maybeSendPlaylistSyncData() {
try {
if (window.__jumpKeyPlaylistSyncSent) return;
const url = new URL(window.location.href);
let source = url.searchParams.get('jumpkey_sync');
if (!source && url.hash) {
const hashMatch = url.hash.match(/(?:#|&)?jumpkey_sync=([^&]+)/);
source = hashMatch ? decodeURIComponent(hashMatch[1]) : null;
}
if (!source || (source !== 'watchLater' && source !== 'liked')) return;
window.__jumpKeyPlaylistSyncSent = true;
const payload = await extractPlaylistVideosForSync();
payload.action = 'playlistSyncData';
payload.source = source;
chrome.runtime.sendMessage(payload, (response) => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey][SYNC] playlist sync message failed:', chrome.runtime.lastError);
} else {
console.log('[JumpKey][SYNC] playlist sync message response:', response);
}
});
} catch (e) {
console.warn('[JumpKey][SYNC] maybeSendPlaylistSyncData failed:', e);
}
}
maybeSendPlaylistSyncData();
window.addEventListener('popstate', maybeSendPlaylistSyncData);
window.addEventListener('yt-navigate-finish', maybeSendPlaylistSyncData);
setTimeout(maybeSendPlaylistSyncData, 2800);
// compute classes for a given thumbnail element; mimics the CRX bundle's logic
function getButtonClasses(node) {
const classes = ['jumpkey-btn', 'watch-later-btn'];
const tag = node.tagName;
if (tag === 'YTD-RICH-ITEM-RENDERER' || tag === 'YTD-VIDEO-RENDERER' || tag === 'YTD-GRID-VIDEO-RENDERER') {
classes.push('in-thumbnail');
}
if (tag === 'YTD-PLAYLIST-VIDEO-RENDERER') {
classes.push('in-playlist');
}
if (tag === 'YTD-NOTIFICATION-RENDERER') {
classes.push('in-notification');
if (node.offsetHeight < 100) classes.push('spaced');
}
if (node.classList.contains('ytp-videowall-still')) {
classes.push('in-endscreen-suggested');
}
if (node.classList.contains('ytp-modern-videowall-still')) {
classes.push('in-mod-endscreen-suggested');
}
if (node.id === 'top-level-buttons-computed') {
classes.push('in-video-detail');
}
try {
const theme = window.ytcfg?.get('INNERTUBE_CONTEXT')?.client?.userInterfaceTheme;
if (theme === 'USER_INTERFACE_THEME_DARK') classes.push('dark');
if (theme === 'USER_INTERFACE_THEME_LIGHT') classes.push('light');
} catch (e) {
// ignore
}
return classes.join(' ');
}
// if we later obtain the icon data URL after buttons were already inserted,
// replace text-only buttons with the image
function refreshButtonsWithIcon(iconDataUrl) {
if (!iconDataUrl) return;
document.querySelectorAll('.jumpkey-btn').forEach((btn) => {
if (!btn.querySelector('img')) {
try {
const img = document.createElement('img');
img.src = iconDataUrl;
img.alt = 'Salvar para assistir mais tarde';
img.style.pointerEvents = 'none';
img.style.width = '100%';
img.style.height = '100%';
img.style.objectFit = 'contain';
btn.textContent = '';
btn.appendChild(img);
} catch (e) {
// ignore
}
}
});
}
// createJumpKeyButton implementation lives in content-video.js
function populateAnchorOnButton(btn, targetElem) {
// tenta encontrar um <a> com link de vídeo dentro do target
try {
const link = targetElem.querySelector('a') || targetElem.closest('a');
if (link && link.href) btn.__jumpkey_anchor_href = link.href;
} catch (e) {
// ignore
}
}
// YouTube video IDs are 11 characters of [A-Za-z0-9_-].
// the site’s own watch‑later buttons carry data-video-id attributes
// matching this pattern; use as a sanity check so we don't grab "any
// old button" that happens to sprout a similar attribute.
function isLikelyYoutubeVideoId(id) {
return typeof id === 'string' && /^[A-Za-z0-9_-]{11}$/.test(id);
}
function handleFullscreenExit() {
// pause the expensive mutation observer while we're dealing with a
// fullscreen change; a couple of seconds is enough to ride out the
// page’s re-layout.
try {
if (jumpKeyGlobalState) {
jumpKeyGlobalState.insertionPauseUntil = Date.now() + 1500;
}
} catch (e) {
// ignore
}
// When a switch is requested via shortcut, YouTube may briefly exit
// document fullscreen during navigation. Don't remove expanded mode while
// that's happening.
if (window.__jumpKeyPreserveFullscreen) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: preserveFullscreen active, skipping removal.');
return;
}
if (!listingShortsModeActive && !listingLongVideoModeActive) {
clearTimeout(listingFullscreenExitValidation);
listingFullscreenExitValidation = null;
console.log('[JumpKey][DEBUG] handleFullscreenExit: Nenhum modo expandido ativo, nada a remover.');
return;
}
if (listingLongVideoModeActive) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Modo expandido longo ativo, não removendo.');
return;
}
// Não remove se ainda está em fullscreen
if (document.fullscreenElement) {
clearTimeout(listingFullscreenExitValidation);
listingFullscreenExitValidation = null;
console.log('[JumpKey][DEBUG] handleFullscreenExit: Ainda em fullscreen, não removendo modo expandido.');
return;
}
// Verifica se a janela saiu do fullscreen
if (!isLikelyWindowFullscreen()) {
// Se aplicou expandido recentemente, evita falso positivo
try {
if (listingLastAppliedExpandedAt && (Date.now() - listingLastAppliedExpandedAt) < 2000) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Remoção ignorada, dentro do período de tolerância após expandido.');
return;
}
} catch (e) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Erro ao checar tolerância:', e);
}
// Se não há validação pendente, inicia uma
if (!listingFullscreenExitValidation) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Possível saída de fullscreen detectada, aguardando validação (300ms)...');
listingFullscreenExitValidation = setTimeout(() => {
// Checa novamente após breve espera
if (!isLikelyWindowFullscreen()) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Confirmado saída de fullscreen após validação rápida, removendo modo expandido.');
// Corrige tamanho da janela para 100% (caso tenha ficado em 50%)
try {
if (window.outerWidth && window.screen && window.screen.availWidth) {
// Só ajusta se a janela está menor que 90% da largura disponível
if (window.outerWidth < window.screen.availWidth * 0.9) {
window.resizeTo(window.screen.availWidth, window.outerHeight);
console.log('[JumpKey][DEBUG] handleFullscreenExit: resizeTo aplicado para restaurar largura total da janela:', window.outerWidth, window.outerHeight);
} else {
console.log('[JumpKey][DEBUG] handleFullscreenExit: largura da janela já está ok:', window.outerWidth);
}
} else {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Não foi possível obter dimensões da janela para resize.');
}
} catch (e) {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Erro ao tentar resizeTo:', e);
}
if (listingShortsModeActive) {
removerModoExpandido();
console.log('[JumpKey][DEBUG] handleFullscreenExit: Modo shorts expandido removido.');
}
if (listingLongVideoModeActive) {
removerModoExpandidoLongo();
console.log('[JumpKey][DEBUG] handleFullscreenExit: Modo long video expandido removido.');
}
} else {
console.log('[JumpKey][DEBUG] handleFullscreenExit: Falso alarme, voltou para fullscreen durante validação.');
}
listingFullscreenExitValidation = null;
}, 300);
}
} else {
// Se voltou para fullscreen, cancela validação
if (listingFullscreenExitValidation) {
clearTimeout(listingFullscreenExitValidation);
listingFullscreenExitValidation = null;
console.log('[JumpKey][DEBUG] handleFullscreenExit: Validação cancelada, voltou para fullscreen.');
}
}
}
function waitForElement(selector, timeout = 5000) {
return new Promise((resolve) => {
const el = document.querySelector(selector);
if (el) {
resolve(el);
return;
}
const observer = new MutationObserver(() => {
const el = document.querySelector(selector);
if (el) {
observer.disconnect();
resolve(el);
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
setTimeout(() => {
observer.disconnect();
resolve(null);
}, timeout);
});
}
async function advanceToNextShort(maxAttempts = 8, intervalMs = 140) {
const selectors = [
'button[aria-label*="Próximo vídeo" i]',
'button[aria-label*="próximo" i]',
'button[aria-label*="Next video" i]',
'ytd-shorts button.yt-spec-button-shape-next[aria-label]'
];
const findButton = () => {
for (const selector of selectors) {
const button = document.querySelector(selector);
if (!button) continue;
const disabled = button.disabled || button.getAttribute('aria-disabled') === 'true';
if (!disabled) {
return button;
}
}
return null;
};
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const nextButton = findButton();
if (nextButton) {
nextButton.click();
console.log('[JumpKey] advanceToNextShort: next button clicked on attempt', attempt);
return { status: 'advanced', attempt };
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
console.warn('[JumpKey] advanceToNextShort: next button not found');
return { status: 'not-found' };
}
function needsExpandedModeRefresh() {
if (!listingShortsModeActive || !isShortsPage()) {
return false;
}
if (!document.getElementById('js-shorts-fullscreen-fix')) {
return true;
}
const app = document.querySelector('ytd-app');
if (app && !app.hasAttribute('masthead-hidden')) {
return true;
}
const shortsContainer = document.querySelector('ytd-shorts');
if (shortsContainer) {
if (shortsContainer.style.width !== '100vw' || shortsContainer.style.height !== '100vh') {
return true;
}
}
return false;
}
function aplicarModoExpandido(options = {}) {
const {
source = 'unknown',
force = false,
preserveActivationTimestamp = false
} = options;
if (listingApplyInProgress && !force) {
console.log('[JumpKey] aplicarModoExpandido ignored (apply already in progress) source:', source);
return;
}
if (!force && listingShortsModeActive && !needsExpandedModeRefresh()) {
return;
}
listingApplyInProgress = true;
try {
console.log('[JumpKey] Starting aplicarModoExpandido');
const styleNode = document.getElementById('js-shorts-fullscreen-fix');
if (!styleNode) {
listingCustomStyle = document.createElement('style');
listingCustomStyle.id = 'js-shorts-fullscreen-fix';
listingCustomStyle.textContent = `
/* Prevent body scroll during expanded mode */
body {
overflow: hidden !important;
}
/* 1. Hide Header, Sidebar, Search Bar e Masthead */
#masthead-container,
ytd-masthead,
ytd-mini-guide-renderer,
#guide {
display: none !important;
}
/* 2. Zero spaces and force container to viewport size */
ytd-app {
--ytd-masthead-height: 0px !important;
--ytd-persistent-guide-width: 0px !important;
}
ytd-app[guide-persistent-and-visible] ytd-page-manager.ytd-app {
margin-left: 0 !important;
}
ytd-shorts {
--ytd-shorts-player-height: 100vh;
--ytd-shorts-player-width: 100vw;
}
#page-manager.ytd-app,
ytd-shorts,
#contentContainer.ytd-shorts,
ytd-shorts #shorts-container.ytd-shorts {
margin-top: 0 !important;
padding: 0 !important;
width: 100vw !important;
height: 100vh !important;
}
/* 3. Expand Renderer and Video */
ytd-reel-video-renderer,
.video-container.ytd-reel-video-renderer,
#player-container.ytd-reel-video-renderer {
width: 100% !important;
height: 100% !important;
max-width: none !important;
max-height: none !important;
}
/* solicited: make overlay full height and center short renderer */
#reel-overlay-container.ytd-shorts {
height: 100% !important;
}
ytd-reel-video-renderer {
align-items: center !important;
}
/* force the actual player and video tag to expand as well; YouTube
frequently applies inline width/height, so we need !important rules */
.html5-video-player,
.html5-video-player .html5-video-container,
.html5-video-player .html5-main-video {
width: 100vw !important;
height: 100vh !important;
max-width: 100% !important;
max-height: none !important;
}
.ytp-fit-cover-video .html5-main-video {
width: calc((100vh - 6px) * var(--ytd-shorts-player-ratio)) !important;
height: calc(100vh - 6px) !important;
}
ytd-reel-video-renderer {
--ytd-shorts-player-height: calc(100vh - 6px) !important;
--ytd-shorts-player-width: min(calc((100vh - 6px) * var(--ytd-shorts-player-ratio-default, var(--ytd-shorts-player-ratio))), calc(100vw - var(--ytd-current-guide-width) - 52px)) !important;
}
`;
document.head.appendChild(listingCustomStyle);
console.log('[JumpKey] CSS applied (style id:', listingCustomStyle.id, ', length:', (listingCustomStyle.textContent || '').length, ')');
// Monitor head to detect if the style is removed by page scripts
try {
const headObserver = new MutationObserver((records) => {
for (const rec of records) {
for (const node of rec.removedNodes) {
if (node && node.id === 'js-shorts-fullscreen-fix') {
console.warn('[JumpKey] CSS node was removed from head by page.');
}
}
}
});
headObserver.observe(document.head, { childList: true });
// disconnect after 30s to avoid leaking observers
setTimeout(() => headObserver.disconnect(), 30000);
} catch (err) {
console.warn('[JumpKey] Failed to attach head observer:', err);
}
} else {
listingCustomStyle = styleNode;
}
// Apply attributes on ytd-app
const app = document.querySelector('ytd-app');
if (app) {
app.setAttribute('masthead-hidden', '');
app.removeAttribute('mini-guide-visible');
console.log('[JumpKey] aplicarModoExpandido - ytd-app attributes updated');
} else {
console.warn('[JumpKey] ytd-app not found when applying expanded mode');
}
// Force hide visible elements
const masterheadContainer = document.getElementById('masthead-container');
if (masterheadContainer) {
masterheadContainer.style.display = 'none';
console.log('[JumpKey] masthead-container hidden');
}
// Force ytd-shorts to fill viewport
const shortsContainer = document.querySelector('ytd-shorts');
if (shortsContainer) {
shortsContainer.style.width = '100vw';
shortsContainer.style.height = '100vh';
shortsContainer.style.margin = '0';
shortsContainer.style.padding = '0';
console.log('[JumpKey] ytd-shorts forced to 100vw x 100vh');
}
const wasShortsModeActive = listingShortsModeActive;
listingShortsModeActive = true;
listingLongVideoModeActive = false;
if (!wasShortsModeActive && !preserveActivationTimestamp) {
listingLastAppliedExpandedAt = Date.now();
}
try {
if (window.location.hostname.includes('youtube.com') && /^\/shorts\/?$/.test(window.location.pathname)) {
console.log('[JumpKey] Expanded mode applied on Shorts home (/shorts without video ID)');
}
} catch (error) {
// ignore logging guard errors
}
// Diagnóstico: loga estado de fullscreen e dimensões
try {
const availW = screen.availWidth, availH = screen.availHeight;
const winW = window.innerWidth, winH = window.innerHeight;
const scrW = screen.width, scrH = screen.height;
const likelyFS = isLikelyWindowFullscreen ? isLikelyWindowFullscreen() : 'n/a';
console.log('[JumpKey][DIAG] Fullscreen check após aplicar modo expandido:', {
isLikelyWindowFullscreen: likelyFS,
windowInner: { w: winW, h: winH },
screenAvail: { w: availW, h: availH },
screen: { w: scrW, h: scrH },
documentFullscreenElement: !!document.fullscreenElement
});
} catch (e) {
console.warn('[JumpKey][DIAG] Erro ao logar diagnóstico de fullscreen:', e);
}
console.log('[JumpKey] aplicarModoExpandido completed');
} finally {
listingApplyInProgress = false;
}
}
function removerModoExpandido() {
listingShortsModeActive = false;
listingLastAppliedExpandedAt = 0;
const styleNode = document.getElementById('js-shorts-fullscreen-fix');
if (styleNode) {
styleNode.remove();
listingCustomStyle = null;
console.log('[JumpKey] Removed custom style tag');
}
// Force remove any inline styles that might persist
document.body.style.removeProperty('overflow');
// Explicitly restore header visibility - use requestAnimationFrame to ensure it happens after YouTube's event handlers
const forceRestoreUI = () => {
const masterheadContainer = document.getElementById('masthead-container');
if (masterheadContainer) {
// Remove ALL inline styles to let YouTube's default styling take over
masterheadContainer.removeAttribute('style');
//masterheadContainer.style.setProperty('position', 'static', 'important');
masterheadContainer.style.setProperty('display', 'block', 'important');
console.log('[JumpKey] masthead-container inline styles removed');
}
// Restore guide/sidebar visibility
const guide = document.getElementById('guide');
if (guide) {
guide.removeAttribute('style');
console.log('[JumpKey] guide inline styles removed');
}
const miniGuide = document.querySelector('ytd-mini-guide-renderer');
if (miniGuide) {
miniGuide.removeAttribute('style');
console.log('[JumpKey] mini-guide inline styles removed');
}
const app = document.querySelector('ytd-app');
if (app) {
// Remove all masthead-related attributes
app.removeAttribute('masthead-hidden');
app.removeAttribute('opened');
app.removeAttribute('mini-guide-visible');
// Reset CSS variables to defaults
app.style.removeProperty('--ytd-masthead-height');
app.style.removeProperty('--ytd-persistent-guide-width');
console.log('[JumpKey] ytd-app attributes and CSS variables reset');
}
};
// Execute immediately
forceRestoreUI();
// And again after YouTube's event handlers run
requestAnimationFrame(() => {
requestAnimationFrame(() => {
forceRestoreUI();
console.log('[JumpKey] UI restoration forced after YouTube event queue');
});
});
const selectorsToReset = [
'ytd-shorts',
'#page-manager.ytd-app',
'ytd-reel-video-renderer',
'.video-container.ytd-reel-video-renderer',
'#player-container.ytd-reel-video-renderer',
'#shorts-container.ytd-shorts',
'#contentContainer.ytd-shorts'
];
selectorsToReset.forEach(sel => {
const el = document.querySelector(sel);
if (el) {
el.style.removeProperty('width');
el.style.removeProperty('height');
el.style.removeProperty('margin-top');
el.style.removeProperty('margin');
el.style.removeProperty('padding');
el.style.removeProperty('--ytd-shorts-player-height');
el.style.removeProperty('--ytd-shorts-player-width');
el.style.removeProperty('max-width');
el.style.removeProperty('max-height');
}
});
const longVideoCleanupSelectors = [
'#full-bleed-container.ytd-watch-flexy',
'.jumpkey-long-expanded'
];
const inlinePropsToClear = [
'position',
'top',
'left',
'right',
'bottom',
'width',
'height',
'margin',
'padding',
'min-width',
'min-height',
'max-width',
'max-height',
'z-index',
'object-fit'
];
longVideoCleanupSelectors.forEach((sel) => {
const el = document.querySelector(sel);
if (el) {
inlinePropsToClear.forEach((prop) => el.style.removeProperty(prop));
el.classList.remove('jumpkey-long-expanded');
}
});
const mediaElements = document.querySelectorAll(`${longVideoCleanupSelectors.join(', ')} video, ${longVideoCleanupSelectors.join(', ')} .html5-main-video`);
mediaElements.forEach((media) => {
inlinePropsToClear.forEach((prop) => media.style.removeProperty(prop));
});
console.log('[JumpKey] removerModoExpandido completed, triggering resize');
window.dispatchEvent(new Event('resize'));
}
function aplicarModoExpandidoLongo() {
// Detecta o container do player+UI automaticamente
const playerContainer = typeof findPlayerContainer === 'function' ? findPlayerContainer() : null;
if (!playerContainer) {
console.warn('[JumpKey] Player container não encontrado, fallback para #full-bleed-container');
}
// Remove estilo antigo se existir
if (listingLongVideoStyle) {
listingLongVideoStyle.remove();
listingLongVideoStyle = null;
}
// Cria novo estilo para o container detectado
listingLongVideoStyle = document.createElement('style');
listingLongVideoStyle.id = 'js-long-video-fullscreen-fix';
let selector = playerContainer ? '' : '#full-bleed-container.ytd-watch-flexy';
if (playerContainer) {
// Adiciona uma classe temporária para garantir seleção única
playerContainer.classList.add('jumpkey-long-expanded');
selector = '.jumpkey-long-expanded';
}
listingLongVideoStyle.textContent = `
body {
overflow: hidden !important;
}
ytd-masthead {
display: none !important;
}
${selector} {
position: fixed !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
bottom: 0 !important;
width: 100vw !important;
height: 100vh !important;
margin: 0 !important;
padding: 0 !important;
max-width: none !important;
max-height: none !important;
z-index: 999999 !important;
background: #000 !important;
}
#below, #secondary {
display: none !important;
}
${selector} video, ${selector} .html5-main-video {
width: 100vw !important;
height: 100vh !important;
max-width: 100vw !important;
max-height: 100vh !important;
object-fit: contain !important;
background: #000 !important;
}
${selector} video {
left: 0 !important;
}
`;
document.head.appendChild(listingLongVideoStyle);
listingLongVideoModeActive = true;
listingShortsModeActive = false;
listingLastAppliedExpandedAt = Date.now();
console.log('[JumpKey] aplicarModoExpandidoLongo - mode activated at', listingLastAppliedExpandedAt, 'selector:', selector);
}
function removerModoExpandidoLongo() {
listingLongVideoModeActive = false;
listingLastAppliedExpandedAt = 0;
const styleNode = document.getElementById('js-long-video-fullscreen-fix');
if (styleNode) {
styleNode.remove();
listingLongVideoStyle = null;
}
const shortsStyle = document.getElementById('js-shorts-fullscreen-fix');
if (shortsStyle) {
shortsStyle.remove();
listingCustomStyle = null;
}
// Restore body overflow
document.body.style.removeProperty('overflow');
// Restore UI elements - use requestAnimationFrame to ensure it happens after YouTube's event handlers
const forceRestoreUI = () => {
const masterheadContainer = document.getElementById('masthead-container');
if (masterheadContainer) {
masterheadContainer.removeAttribute('style');
//masterheadContainer.style.setProperty('position', 'static', 'important');
masterheadContainer.style.setProperty('display', 'block', 'important');
}
const guide = document.getElementById('guide');
if (guide) {
guide.removeAttribute('style');
}
const miniGuide = document.querySelector('ytd-mini-guide-renderer');
if (miniGuide) {
miniGuide.removeAttribute('style');
}
const app = document.querySelector('ytd-app');
if (app) {
app.removeAttribute('masthead-hidden');
app.removeAttribute('opened');
app.removeAttribute('mini-guide-visible');
app.style.removeProperty('--ytd-masthead-height');
app.style.removeProperty('--ytd-persistent-guide-width');
}
};
// Execute immediately
forceRestoreUI();
// And again after YouTube's event handlers run
requestAnimationFrame(() => {
requestAnimationFrame(() => {
forceRestoreUI();
});
});
console.log('[JumpKey] Long video fullscreen mode removed, body overflow restored');
window.dispatchEvent(new Event('resize'));
}
async function setReelFullscreen(enabled) {
console.log('[JumpKey] ========== setReelFullscreen called with enabled:', enabled, '==========');
// return an object describing what we tried; callers expect a promise
if (enabled) {
try {
// When switching tabs, the page may not yet have fully initialized.
// Wait for the shorts container to exist before applying expanded mode.
const shortsRoot = await waitForElement('ytd-shorts', 2000);
if (!shortsRoot) {
console.warn('[JumpKey] setReelFullscreen: shorts container not found, will retry later');
// Schedule a retry after a short delay in case it appears soon.
setTimeout(() => {
try {
if (isShortsPage()) {
aplicarModoExpandido({ source: 'setReelFullscreen-retry', force: true });
console.log('[JumpKey] Expanded mode applied on retry');
}
} catch (err) {
console.warn('[JumpKey] Retry applying expanded mode failed:', err);
}
}, 80);
return { status: 'deferred', reason: 'shorts-not-ready' };
}
aplicarModoExpandido({ source: 'setReelFullscreen', force: true });
console.log('[JumpKey] Expanded mode applied');
return { status: 'applied', method: 'expanded-mode' };
} catch (err) {
console.warn('[JumpKey] Error applying expanded mode:', err);
return { status: 'error', error: err.message };
}
} else {
try {
removerModoExpandido();
console.log('[JumpKey] Expanded mode removed');
return { status: 'removed' };
} catch (err) {
console.warn('[JumpKey] Error removing expanded mode:', err);
return { status: 'error', error: err.message };
}
}
}
// Handle Escape key: exit native fullscreen and remove any expanded modes
async function handleEscapeKey() {
try {
console.log('[JumpKey] Escape pressed - attempting to exit fullscreen/expanded mode');
// Exit Document fullscreen if active
try {
if (document.fullscreenElement) {
await document.exitFullscreen();
console.log('[JumpKey] Exited document fullscreen');
}
} catch (err) {
console.warn('[JumpKey] Failed to exit document fullscreen:', err);
}
// Immediately remove any expanded mode that may still be active,
// even if the internal active flag is stale.
try {
removerModoExpandido();
console.log('[JumpKey] Removed shorts expanded mode via Escape');
} catch (e) {
console.warn('[JumpKey] Error removing shorts expanded mode:', e);
}
try {
removerModoExpandidoLongo();
console.log('[JumpKey] Removed long video expanded mode via Escape');
} catch (e) {
console.warn('[JumpKey] Error removing long video expanded mode:', e);
}
if (listingFullscreenExitValidation) {
clearTimeout(listingFullscreenExitValidation);
listingFullscreenExitValidation = null;
console.log('[JumpKey][DEBUG] handleEscapeKey: cancelled pending fullscreen-exit validation');
}
// Garante que a janela saia do fullscreen (não só o documento)
try {
if (chrome && chrome.windows && chrome.windows.getCurrent && chrome.windows.update) {
chrome.windows.getCurrent((win) => {
if (win && win.state === 'fullscreen') {
// Prefer maximizing instead of normalizing to avoid ending up in a half-width window.
chrome.windows.update(win.id, { state: 'maximized' }, () => {
console.log('[JumpKey][DEBUG] handleEscapeKey: chrome.windows.update chamado para sair do fullscreen (maximized):', win.id);
});
} else {
console.log('[JumpKey][DEBUG] handleEscapeKey: Janela não está em fullscreen (estado atual):', win && win.state);
}
});
}
} catch (e) {
console.log('[JumpKey][DEBUG] handleEscapeKey: Erro ao tentar sair do fullscreen da janela:', e);
}
try {
if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
chrome.runtime.sendMessage({ action: 'exitFullscreenWindow' }, (resp) => {
if (chrome.runtime.lastError) {
console.debug('[JumpKey] exitFullscreenWindow lastError:', chrome.runtime.lastError && chrome.runtime.lastError.message);
} else {
console.log('[JumpKey] background exit fullscreen response:', resp);
}
});
}
} catch (e) {
// ignore
}
} catch (err) {
console.error('[JumpKey] handleEscapeKey error:', err);
}
}