Repository navigation
Expand file tree
/
Copy pathcontent-video.js
More file actions
1327 lines (1148 loc) · 45.3 KB
/
Copy pathcontent-video.js
File metadata and controls
1327 lines (1148 loc) · 45.3 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
const LIKE_PATH_D = 'M3,11h3v10H3V11z M18.77,11h-4.23l1.52-4.94C16.38,5.03,15.54,4,14.38,4c-0.58,0-1.14,0.24-1.52,0.65L7,11v10h10.43 c1.06,0,1.98-0.67,2.19-1.61l1.34-6C21.23,12.15,20.18,11,18.77,11z';
const DISLIKE_PATH_D = 'M17,4h-1H6.57C5.5,4,4.59,4.67,4.38,5.61l-1.34,6C2.77,12.85,3.82,14,5.23,14h4.23l-1.52,4.94C7.62,19.97,8.46,21,9.62,21 c0.58,0,1.14-0.24,1.52-0.65L17,14h4V4H17z M10.4,19.67C10.21,19.88,9.92,20,9.62,20c-0.26,0-0.5-0.11-0.63-0.3 c-0.07-0.1-0.15-0.26-0.09-0.47l1.52-4.94l0.4-1.29H9.46H5.23c-0.41,0-0.77-0.28-0.86-0.68l1.34-6C5.81,5.15,6.16,5,6.57,5H16v8.59 l-4.08,4.43C11.7,18.21,11.07,18.44,10.4,19.67z';
function createThumbIcon(isLike) {
const NS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('width', '96');
svg.setAttribute('height', '96');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('focusable', 'false');
const path = document.createElementNS(NS, 'path');
path.setAttribute('fill', 'white');
path.setAttribute('d', isLike ? LIKE_PATH_D : DISLIKE_PATH_D);
svg.appendChild(path);
return svg;
}
function showIndicator(isLike) {
if (typeof(window.findPlayerContainer) !== 'function' && typeof(window.findPlayerContainer) === 'function') {
window.findPlayerContainer = findPlayerContainer;
}
let player = findPlayerContainer();
const usePageOverlay = !player;
if (usePageOverlay) {
// Some YouTube layouts (watch pages) may not expose a stable player container,
// so fall back to a fixed overlay in the viewport.
player = document.body;
}
let overlay = player.querySelector('.jumpkey-thumb-indicator');
if (!overlay) {
overlay = document.createElement('div');
overlay.className = 'jumpkey-thumb-indicator';
overlay.style.position = usePageOverlay ? 'fixed' : 'absolute';
overlay.style.left = '50%';
overlay.style.top = '50%';
overlay.style.transform = 'translate(-50%, -50%)';
overlay.style.zIndex = '9999';
overlay.style.pointerEvents = 'none';
overlay.style.transition = 'opacity 0.3s';
overlay.style.opacity = '0';
overlay.style.display = 'flex';
overlay.style.alignItems = 'center';
overlay.style.justifyContent = 'center';
overlay.style.padding = '2.5%';
overlay.style.borderRadius = '50%';
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
player.appendChild(overlay);
}
overlay.replaceChildren(createThumbIcon(isLike));
overlay.style.opacity = '1';
// Remove após 900ms
setTimeout(() => {
overlay.style.opacity = '0';
setTimeout(() => { if (overlay.parentNode) overlay.parentNode.removeChild(overlay); }, 350);
}, 900);
}
// ==== GARANTE VARIÁVEIS GLOBAIS NO TOPO ====
let outOfMemoryCheckTimeout;
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,
reportLoadHandler: null,
reportNavigateHandler: null,
reportVisibilityHandler: null,
cssObserver: null,
videoObserver: null,
locationPollInterval: null,
lastObservedLocationHref: '',
lastHistoryReport: null,
lastDurationReportKey: null
});
let lastAppliedExpandedAt = 0;
let shortsModeActive = false;
let longVideoModeActive = false;
let fullscreenExitValidation = null;
let customStyle = null;
let longVideoStyle = null;
let observedRootNode = null;
let currentVideoId = null;
let pendingVideoReportTimeout = null;
let pendingVideoReportRaf = null;
console.log('[JumpKey] ========== CONTENT SCRIPT LOADED ==========');
console.log('[JumpKey] URL:', window.location.href);
console.log('[JumpKey] document.readyState:', document.readyState);
// ========== ESC para sair do fullscreen da janela ==========
function handleEscToExitFullscreen(event) {
if (event.key === 'Escape' && !isInputElement(document.activeElement)) {
try {
if (document.fullscreenElement) {
document.exitFullscreen().catch((e) => {
console.warn('[JumpKey] Error exiting native fullscreen:', e);
});
}
} catch (e) {
console.warn('[JumpKey] handleEscToExitFullscreen fallback error:', e);
}
const exitBrowserFullscreen = () => {
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.message);
} else {
console.log('[JumpKey] background exitFullscreenWindow response:', resp);
}
});
}
} catch (e) {
console.warn('[JumpKey] Failed to send exitFullscreenWindow message:', e);
}
try {
if (chrome.windows && chrome.windows.getCurrent && chrome.windows.update) {
chrome.windows.getCurrent((win) => {
if (win && win.state && win.state !== 'normal' && win.state !== 'maximized') {
chrome.windows.update(win.id, { state: 'maximized' }, (updated) => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] Falha ao restaurar janela maximizada:', chrome.runtime.lastError);
} else {
console.log('[JumpKey] Janela restaurada para maximizada após ESC');
}
});
}
});
}
} catch (e) {
console.warn('[JumpKey] Falha ao restaurar janela maximizada diretamente:', e);
}
};
// Tenta sair do fullscreen de navegador imediatamente e também via background.
exitBrowserFullscreen();
// Sempre tente remover qualquer modo expandido ativo ao pressionar ESC.
try {
if (typeof window.removerModoExpandido === 'function') {
window.removerModoExpandido();
console.log('[JumpKey] removerModoExpandido chamado após ESC');
}
if (typeof window.removerModoExpandidoLongo === 'function') {
window.removerModoExpandidoLongo();
console.log('[JumpKey] removerModoExpandidoLongo chamado após ESC');
}
} catch (e) {
console.warn('[JumpKey] Cleanup do modo expandido após ESC falhou:', e);
}
}
}
// Adiciona o listener apenas uma vez
if (!jumpKeyGlobalState.keydownHandlerEscFullscreen) {
jumpKeyGlobalState.keydownHandlerEscFullscreen = handleEscToExitFullscreen;
document.addEventListener('keydown', handleEscToExitFullscreen, true);
}
if (jumpKeyGlobalState.initialized) {
console.warn('[JumpKey] Duplicate content script init detected; cleaning old listeners/observers.');
// Cleanup old listeners to prevent accumulation
if (jumpKeyGlobalState.resizeHandler) {
window.removeEventListener('resize', jumpKeyGlobalState.resizeHandler);
}
if (jumpKeyGlobalState.fullscreenchangeHandler) {
document.removeEventListener('fullscreenchange', jumpKeyGlobalState.fullscreenchangeHandler);
}
if (jumpKeyGlobalState.DOMContentLoadedHandler) {
window.removeEventListener('DOMContentLoaded', jumpKeyGlobalState.DOMContentLoadedHandler);
}
if (jumpKeyGlobalState.loadHandler) {
window.removeEventListener('load', jumpKeyGlobalState.loadHandler);
}
if (jumpKeyGlobalState.reportLoadHandler) {
window.removeEventListener('load', jumpKeyGlobalState.reportLoadHandler);
}
if (jumpKeyGlobalState.reportNavigateHandler) {
window.removeEventListener('yt-navigate-finish', jumpKeyGlobalState.reportNavigateHandler);
}
if (jumpKeyGlobalState.reportVisibilityHandler) {
document.removeEventListener('visibilitychange', jumpKeyGlobalState.reportVisibilityHandler);
}
if (jumpKeyGlobalState.keydownHandler) {
document.removeEventListener('keydown', jumpKeyGlobalState.keydownHandler);
}
if (jumpKeyGlobalState.popstateHandler) {
window.removeEventListener('popstate', jumpKeyGlobalState.popstateHandler);
}
if (jumpKeyGlobalState.hashchangeHandler) {
window.removeEventListener('hashchange', jumpKeyGlobalState.hashchangeHandler);
}
if (jumpKeyGlobalState.ytNavigationHandler) {
window.removeEventListener('yt-navigate-finish', jumpKeyGlobalState.ytNavigationHandler);
}
if (jumpKeyGlobalState.pagehideHandler) {
window.removeEventListener('pagehide', jumpKeyGlobalState.pagehideHandler);
}
if (jumpKeyGlobalState.cssObserver) {
jumpKeyGlobalState.cssObserver.disconnect();
}
if (jumpKeyGlobalState.videoObserver) {
jumpKeyGlobalState.videoObserver.disconnect();
}
if (jumpKeyGlobalState.watchObserver) {
try { jumpKeyGlobalState.watchObserver.disconnect(); } catch (e) {}
jumpKeyGlobalState.watchObserver = null;
}
if (jumpKeyGlobalState.watchInterval) {
try { clearInterval(jumpKeyGlobalState.watchInterval); } catch (e) {}
jumpKeyGlobalState.watchInterval = null;
}
if (jumpKeyGlobalState.locationPollInterval) {
try { clearInterval(jumpKeyGlobalState.locationPollInterval); } catch (e) {}
jumpKeyGlobalState.locationPollInterval = null;
}
// Cleanup pending timeouts
if (pendingVideoReportTimeout) {
clearTimeout(pendingVideoReportTimeout);
pendingVideoReportTimeout = null;
}
if (pendingVideoReportRaf) {
cancelAnimationFrame(pendingVideoReportRaf);
pendingVideoReportRaf = null;
}
if (fullscreenExitValidation) {
clearTimeout(fullscreenExitValidation);
fullscreenExitValidation = null;
}
if (outOfMemoryCheckTimeout) {
clearTimeout(outOfMemoryCheckTimeout);
outOfMemoryCheckTimeout = null;
}
}
jumpKeyGlobalState.initialized = true;
function isInputElement(element) {
if (!element || !element.tagName) {
return false;
}
const tagName = element.tagName.toLowerCase();
const isEditable = element.isContentEditable;
const isInput = tagName === 'input' || tagName === 'textarea';
const isSelect = tagName === 'select';
return isInput || isEditable || isSelect;
}
// ícone em data URL (24x24) usado pelo CRX original para o overlay de Shorts
const ICON_DATA_URL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAEE0lEQVR4Aa3By4uddx3H8ffn9zznas7MdDJRImZCQzXYTaBQK0IR1xIFBf8FXYgLV4pFvEREd6VQ6oW4aFcFseBCcKUWK8WA1pqkCIoR2iZN0jMznjOZ8zy/3/fjOSeXTp2pN3y9xD67b7ypvYuXRvXlVzZ05cq6oqwymY40mx3RdNJ1p9u1hFIKSmnodqfR709YW90uo9Wb+YFTN3qPPDIebR4P7hBzky9+6dE0Hj+Wrl//kCaTVYGwUUpgwAES+xkQ4jZjbovhcOKNjd+Wzc3Hjpz76gva+ua3N/vP/+YyuQxBgFkyb5FYsjmUAIn9NOhtz86ePV3Xv3/50w4PrcSCELIBc4/NAWLJCEssiTmxUO01q+nChU/UtOW0zZJsZPNvSZg5sSSMESDuCoR2Jg8mcjnOnGxk878SIBtsFsxc055IynlDgGz+H8ScDQhKvCfJXsNmaTTibQYDOt/5Bjq5yX9DLBgi1pPWVo9wR3rwNOljj6K1Ve5KDz9E94dPUH/+szAagYSZE//EHBBxJOnEiUF64BQM+ixo/T7Shx9Gp9+POh2WqorqU2fpPv190ic/DnXF4QyYBdkQflcC9zQYoPceh+EQJBb07g30wQ+wn1ZGdL7wOXpPPU566AzvzIAhSjeRS2LBoLoGJe5JicPo/pN0v3uO7te/go5tcCiDZw2JOduAAfMfm0yJly/i8RYHGBwGk+owkQDZHGQOiKD87OfkHz2Dt7Y5lMEGo1KHNRMGhAGxT5j94qU/kp/8AfHnv/CODAZsEUFblxy7JEgBMgiz4Os34PVrLPjqNfL3zhO/eoElcQixYEMYophSYlq3jSckE5NbaLILJYjfvYS2tqHXJZ9/mvLsT6BpuEsIMyfuEDZzIgxRTNsUcrBT7413t2avvU7d7hJ/3yXtTUkyCdCsIT/zLOJfsDBzhjCUYtpZ0OwFoTSuxxf+dL0Tmd6gIrdjuv2KuiOqWiRBwhiQeIuNuc2ADREi56BtgnavsHerwKC+WU/b9Gr/Vqa0QZ4Vck90uolOR1S1qCqRZCQQtxmBwIYwRIHcmtyapgmaveBWK1In/bWeVsOLzKY4Z2ImSle0HdGpRd2BqhJVJVICiXsMREAElGxKNm1r2ta0LexEj2Hd/0Pd++iZH9947sVzK+10fZgz0QS5Fm0FdSWqClIFKQkJJMBgwAERphQoBdoCe1GxEz2a/vDa+06tPCfmfvGZr52ZXnr1y2U8+Uh5c+d4h6g7Kegm00mmSqZKIBlJGDAiLFqL7ERbEo1TqVaGV/tr/V+u37/2rTM/ffyS2Kf8+kVeu3yle/X5SxvNK387FtlHc1NWyV4ht70opUopUVdkUjVTlaZVim3165uDE0ffOHZy7cbRrWuz3vknuesfnG0T';
const VIDEO_REPORT_DEBOUNCE_MS = 150;
const DEFAULT_SETTINGS = {
customShortcuts: {
switchRandom: ['y'],
likeOnly: ['+'],
dislikeOnly: ['-']
}
};
let customShortcuts = { ...DEFAULT_SETTINGS.customShortcuts };
// Start checking for Out of Memory errors after all variables are initialized
scheduleOutOfMemoryCheck();
function scheduleVideoStateReport(delay = 800) {
setTimeout(() => {
queueReportCurrentVideo();
reportDurationToBackground();
}, delay);
}
// Auto report duration when a YouTube video page loads or navigates
if (jumpKeyGlobalState.reportLoadHandler) {
window.removeEventListener('load', jumpKeyGlobalState.reportLoadHandler);
}
jumpKeyGlobalState.reportLoadHandler = () => {
scheduleVideoStateReport();
};
window.addEventListener('load', jumpKeyGlobalState.reportLoadHandler);
if (jumpKeyGlobalState.reportNavigateHandler) {
window.removeEventListener('yt-navigate-finish', jumpKeyGlobalState.reportNavigateHandler);
}
jumpKeyGlobalState.reportNavigateHandler = () => {
scheduleVideoStateReport();
};
window.addEventListener('yt-navigate-finish', jumpKeyGlobalState.reportNavigateHandler);
if (jumpKeyGlobalState.reportVisibilityHandler) {
document.removeEventListener('visibilitychange', jumpKeyGlobalState.reportVisibilityHandler);
}
jumpKeyGlobalState.reportVisibilityHandler = () => {
if (document.visibilityState === 'visible') {
queueReportCurrentVideo();
reportDurationToBackground();
}
};
document.addEventListener('visibilitychange', jumpKeyGlobalState.reportVisibilityHandler);
// In case the page transitions via History API without events, poll occasionally.
jumpKeyGlobalState.lastObservedLocationHref = window.location.href;
if (jumpKeyGlobalState.locationPollInterval) {
clearInterval(jumpKeyGlobalState.locationPollInterval);
}
jumpKeyGlobalState.locationPollInterval = setInterval(() => {
if (window.location.href !== jumpKeyGlobalState.lastObservedLocationHref) {
jumpKeyGlobalState.lastObservedLocationHref = window.location.href;
queueReportCurrentVideo();
reportDurationToBackground();
}
}, 1200);
function extractVideoId(url) {
if (!url || typeof url !== 'string') {
return null;
}
const shortsMatch = url.match(/\/shorts\/([a-zA-Z0-9_-]+)/);
if (shortsMatch && shortsMatch[1]) {
return shortsMatch[1];
}
const watchMatch = url.match(/[?&]v=([a-zA-Z0-9_-]+)/);
if (watchMatch && watchMatch[1]) {
return watchMatch[1];
}
return null;
}
function getVideoTitle() {
const selectors = [
'ytd-watch-metadata h1 yt-formatted-string',
'h1.ytd-watch-metadata yt-formatted-string',
'yt-formatted-string.style-scope.ytd-watch-metadata',
'yt-formatted-string.title',
'meta[property="og:title"]'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (!element) {
continue;
}
const contentAttr = element.getAttribute && element.getAttribute('content');
const text = typeof contentAttr === 'string' && contentAttr.trim().length > 0
? contentAttr
: (element.textContent || element.innerText || '');
const clean = text.trim();
if (clean) {
return clean;
}
}
return 'Unknown';
}
function normalizeVideoTitle(title) {
return typeof title === 'string' ? title.trim() : '';
}
function isPlaceholderVideoTitle(title) {
const normalized = normalizeVideoTitle(title).toLowerCase();
return normalized === '' || normalized === 'unknown' || normalized === 'início' || normalized === 'inicio' || normalized === 'home' || normalized === 'shorts' || normalized === 'youtube';
}
function shouldSkipVideoHistoryReport(videoId, title) {
const lastReport = jumpKeyGlobalState.lastHistoryReport;
if (!lastReport || lastReport.videoId !== videoId) {
return false;
}
const previousTitle = normalizeVideoTitle(lastReport.title);
const currentTitle = normalizeVideoTitle(title);
if (previousTitle === currentTitle) {
return true;
}
if (!isPlaceholderVideoTitle(previousTitle) && isPlaceholderVideoTitle(currentTitle)) {
return true;
}
return false;
}
function isYoutubeVideoPage() {
try {
const host = window.location.hostname || '';
const path = window.location.pathname || '';
return host.includes('youtube.com') && (path.startsWith('/shorts/') || path.startsWith('/watch'));
} catch (error) {
return /youtube\.com\/(shorts|watch)/.test(window.location.href || '');
}
}
async function reportCurrentVideo() {
if (!chrome.runtime?.id) {
return;
}
if (document.visibilityState !== 'visible') {
return;
}
const url = window.location.href;
const videoId = extractVideoId(url);
if (!videoId) {
return;
}
currentVideoId = videoId;
const title = getVideoTitle();
if (shouldSkipVideoHistoryReport(videoId, title)) {
return;
}
jumpKeyGlobalState.lastHistoryReport = { videoId, title };
console.log('[JumpKey] Current video:', { videoId, title });
chrome.runtime.sendMessage(
{ action: 'saveVideoToHistory', videoId, title },
(response) => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] saveVideoToHistory message error:', {
videoId,
message: chrome.runtime.lastError.message
});
} else {
console.log('[JumpKey] Video saved:', response);
}
}
);
// Attach ended listener on long videos to optionally remove from Watch Later
try {
const videoEl = document.querySelector('video.html5-main-video');
if (videoEl && !videoEl.__srEndedHooked) {
videoEl.__srEndedHooked = true;
videoEl.addEventListener('ended', () => {
try {
console.log('[JumpKey] Video ended event detected for', videoId);
// Check user setting before requesting removal
chrome.storage.sync.get({ autoRemoveWatchedFromWatchLater: true }, (items) => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] Storage get error:', chrome.runtime.lastError);
return;
}
if (items.autoRemoveWatchedFromWatchLater) {
chrome.runtime.sendMessage({ action: 'removeFromYoutubeWatchLater', videoId }, (resp) => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] removeFromYoutubeWatchLater message error:', {
videoId,
message: chrome.runtime.lastError.message
});
} else {
console.log('[JumpKey] Request to remove from Watch Later sent:', resp);
}
});
}
});
} catch (e) {
console.warn('[JumpKey] ended handler error:', e);
}
});
console.log('[JumpKey] Attached ended listener to video element');
}
} catch (e) {
console.warn('[JumpKey] Error attaching ended listener:', e);
}
// 🚫 Verifica se o vídeo tem tags bloqueadas
}
function scheduleReportCurrentVideo(delay = VIDEO_REPORT_DEBOUNCE_MS) {
if (!isYoutubeVideoPage()) {
return;
}
if (pendingVideoReportTimeout) {
return;
}
pendingVideoReportTimeout = setTimeout(() => {
pendingVideoReportTimeout = null;
reportCurrentVideo();
}, delay);
}
function queueReportCurrentVideo() {
if (!isYoutubeVideoPage()) {
return;
}
if (pendingVideoReportRaf) {
return;
}
pendingVideoReportRaf = requestAnimationFrame(() => {
pendingVideoReportRaf = null;
scheduleReportCurrentVideo();
});
}
function getCurrentVideoId() {
const url = window.location.href;
const shortsMatch = url.match(/\/shorts\/([a-zA-Z0-9_-]+)/);
if (shortsMatch && shortsMatch[1]) return shortsMatch[1];
const watchMatch = url.match(/[?&]v=([a-zA-Z0-9_-]+)/);
if (watchMatch && watchMatch[1]) return watchMatch[1];
return null;
}
async function queryDuration() {
try {
const video = document.querySelector('video');
if (video && Number.isFinite(video.duration) && video.duration > 0) {
return Number(video.duration);
}
if (window.ytInitialPlayerResponse?.videoDetails?.lengthSeconds) {
const val = Number(window.ytInitialPlayerResponse.videoDetails.lengthSeconds);
if (Number.isFinite(val) && val > 0) return val;
}
if (window.ytplayer?.config?.args?.length_seconds) {
const val = Number(window.ytplayer.config.args.length_seconds);
if (Number.isFinite(val) && val > 0) return val;
}
const mmeta = document.querySelector('meta[itemprop="duration"]');
if (mmeta && mmeta.content) {
const pt = mmeta.content;
let sec = 0;
const h = pt.match(/(\d+)H/);
if (h) sec += parseInt(h[1], 10) * 3600;
const m = pt.match(/(\d+)M/);
if (m) sec += parseInt(m[1], 10) * 60;
const s = pt.match(/(\d+(?:\.\d+)?)S/);
if (s) sec += Math.floor(parseFloat(s[1]));
if (Number.isFinite(sec) && sec > 0) return sec;
}
} catch (err) {
console.warn('[JumpKey] queryDuration failed:', err);
}
return null;
}
async function reportDurationToBackground() {
const videoId = getCurrentVideoId();
if (!videoId) return;
let duration = null;
const start = Date.now();
while (Date.now() - start < 1600) {
duration = await queryDuration();
if (duration && duration > 0) break;
await new Promise((r) => setTimeout(r, 200));
}
if (duration && duration > 0) {
const durationReportKey = `${videoId}:${Math.round(duration)}`;
if (jumpKeyGlobalState.lastDurationReportKey === durationReportKey) {
return;
}
jumpKeyGlobalState.lastDurationReportKey = durationReportKey;
console.log('[JumpKey] reportVideoDuration emitting', { videoId, duration });
chrome.runtime.sendMessage({ action: 'reportVideoDuration', videoId, duration }, () => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] reportVideoDuration message error:', {
videoId,
duration,
message: chrome.runtime.lastError.message
});
}
});
} else {
console.log('[JumpKey] reportVideoDuration no duration available yet', { videoId, duration });
}
}
function loadShortcutSettings() {
chrome.storage.sync.get(DEFAULT_SETTINGS, (items) => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] Failed to load shortcut settings:', chrome.runtime.lastError);
return;
}
customShortcuts = items.customShortcuts || { ...DEFAULT_SETTINGS.customShortcuts };
console.log('[JumpKey] Custom shortcuts loaded:', customShortcuts);
});
}
function isShortsPage() {
try {
return window.location.hostname.includes('youtube.com') && window.location.pathname.startsWith('/shorts');
} catch (error) {
return /\/shorts(?:\/?$|\?)/.test(window.location.href);
}
}
function getRateButtons() {
// Specific selectors based on working extension patterns
const containerSelectors = [
// Regular video selectors
'ytd-watch-flexy:not([hidden]) #top-level-buttons-computed yt-smartimation',
'ytd-page-manager ytd-segmented-like-dislike-button-renderer yt-smartimation',
'#top-level-buttons-computed li:has(ytd-segmented-like-dislike-button-renderer)',
// Shorts selectors
'reel-action-bar-view-model',
'ytd-reel-video-renderer[is-active] #like-button',
// Mobile fallback
'ytm-shorts-video-renderer li:has(button[aria-label*="like" i])'
];
for (const selector of containerSelectors) {
const container = document.querySelector(selector);
if (container) {
const buttons = [...container.querySelectorAll('button')];
if (buttons.length >= 2) {
return buttons;
}
}
}
return [];
}
function getIsButtonActive(button) {
return button?.getAttribute('aria-pressed') === 'true';
}
function normalizeLabelText(value) {
return (value || '')
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '');
}
function matchActionByAriaLabel(actionType, button) {
const label = normalizeLabelText(button?.getAttribute('aria-label'));
if (!label) {
return false;
}
const likeKeywords = ['like', 'gostei', 'me gusta', 'curtir', 'curti', '赞', '喜歡', '喜欢'];
const dislikeKeywords = ['dislike', 'nao gostei', 'não gostei', 'no me gusta', 'nao curti', 'não curti', '不喜歡', '不喜欢'];
if (actionType === 'like') {
const isLike = likeKeywords.some((keyword) => label.includes(normalizeLabelText(keyword)));
const isDislike = dislikeKeywords.some((keyword) => label.includes(normalizeLabelText(keyword)));
return isLike && !isDislike;
}
return dislikeKeywords.some((keyword) => label.includes(normalizeLabelText(keyword)));
}
function findActionButton(actionType) {
const buttons = getRateButtons();
if (buttons.length === 0) {
return null;
}
// 1) Prefer aria-label matching (multilingual)
for (const button of buttons) {
if (matchActionByAriaLabel(actionType, button)) {
return button;
}
}
// 2) Positional fallback: first is like, second is dislike
if (actionType === 'like' && buttons[0]) {
return buttons[0];
}
if (actionType === 'dislike' && buttons[1]) {
return buttons[1];
}
return null;
}
function applyReactionIfNeeded(actionType) {
const button = findActionButton(actionType);
if (!button) {
console.log(`[JumpKey] ${actionType} button not found`);
return;
}
// Exibe o indicador visual
if (actionType === 'like') showIndicator(true);
if (actionType === 'dislike') showIndicator(false);
// Only click if button is not already active
if (!getIsButtonActive(button)) {
button.click();
button.blur();
console.log(`[JumpKey] ${actionType} applied`);
} else {
console.log(`[JumpKey] ${actionType} already active, skipping`);
}
}
function switchShorts() {
try {
if (!chrome.runtime?.id) {
console.warn('[JumpKey] Runtime not available yet');
return;
}
chrome.runtime.sendMessage({ action: 'switchShorts' }, () => {
if (chrome.runtime.lastError) {
console.warn('[JumpKey] switchShorts message error (extension may have reloaded):', {
message: chrome.runtime.lastError.message
});
}
});
} catch (error) {
console.error('[JumpKey] Error sending message:', error);
}
}
function detectAndReloadOutOfMemory() {
// Check for "Out of Memory" error message on page
const pageText = document.documentElement.innerText || '';
const hasMemoryError = pageText.includes('Out of Memory');
const isBrowserErrorPage = window.location.protocol === 'chrome-error:' || window.location.href.startsWith('chrome-error://');
if (hasMemoryError && isBrowserErrorPage) {
console.log('[JumpKey] Detected Out of Memory error, reloading page...');
window.location.reload();
return true;
}
return false;
}
function scheduleOutOfMemoryCheck() {
if (outOfMemoryCheckTimeout) {
clearTimeout(outOfMemoryCheckTimeout);
}
outOfMemoryCheckTimeout = setTimeout(() => {
if (detectAndReloadOutOfMemory()) {
return;
}
// Check again in 5 seconds
scheduleOutOfMemoryCheck();
}, 5000);
}
function findPrimaryVideoElement() {
const selectors = [
'video.html5-main-video',
'ytd-reel-video-renderer video',
'video'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element instanceof HTMLVideoElement) {
return element;
}
}
return null;
}
function fadeOutCurrentVideoAudio(durationMs = 400, steps = 10) {
return new Promise((resolve) => {
const video = findPrimaryVideoElement();
if (!video) {
console.log('[JumpKey] fadeOutAudio: no video element found, skipping fade');
resolve({ status: 'no-video' });
return;
}
const safeDuration = Math.max(50, Number(durationMs) || 250);
const safeSteps = Math.max(2, Number(steps) || 10);
const initialVolume = Math.max(0, Math.min(1, Number(video.volume)));
const stepInterval = Math.max(10, Math.floor(safeDuration / safeSteps));
if (video.muted || initialVolume <= 0.001) {
video.muted = true;
video.volume = 0;
resolve({ status: 'already-muted' });
return;
}
let currentStep = 0;
const intervalId = setInterval(() => {
currentStep += 1;
const progress = currentStep / safeSteps;
const nextVolume = Math.max(0, initialVolume * (1 - progress));
video.volume = nextVolume;
if (currentStep >= safeSteps || nextVolume <= 0.001) {
clearInterval(intervalId);
video.volume = 0;
video.muted = true;
resolve({ status: 'faded' });
}
}, stepInterval);
});
}
function preserveFullscreenDuringSwitch(durationMs = 5000) {
try {
window.__jumpKeyPreserveFullscreen = true;
setTimeout(() => {
window.__jumpKeyPreserveFullscreen = false;
}, durationMs);
} catch (e) {
// ignore
}
}
function handleShortcutCommand(command) {
if (command === 'switchRandom') {
preserveFullscreenDuringSwitch();
switchShortsRandom();
return;
}
if (command === 'likeOnly') {
applyReactionIfNeeded('like');
return;
}
if (command === 'dislikeOnly') {
applyReactionIfNeeded('dislike');
}
}
function isExtensionContextValid() {
try {
return !!(chrome && chrome.runtime && chrome.runtime.id);
} catch (e) {
return false;
}
}
function switchShortsRandom() {
if (!isExtensionContextValid()) {
console.warn('[JumpKey] Extension context invalidated; reloading content script context');
setTimeout(() => {
window.location.reload();
}, 80);
return;
}
chrome.runtime.sendMessage({ action: 'switchRandom' }, (response) => {
if (chrome.runtime.lastError) {
console.error('[JumpKey] Error:', chrome.runtime.lastError.message);
if (chrome.runtime.lastError.message && chrome.runtime.lastError.message.includes('Extension context invalidated')) {
setTimeout(() => {
window.location.reload();
}, 80);
}
}
});
}
function getShortcutCommand(event) {
const key = event.key;
const code = event.code;
let pressedKey = key;
if (code && code.startsWith('Arrow')) {
pressedKey = code;
} else if (code === 'NumpadAdd') {
pressedKey = '+';
} else if (code === 'NumpadSubtract') {
pressedKey = '-';
}
pressedKey = pressedKey.toLowerCase();
for (const [action, keys] of Object.entries(customShortcuts)) {
const normalizedKeys = keys.map((k) => k.toLowerCase());
if (normalizedKeys.includes(pressedKey)) {
return action;
}
}
return null;
}
function isLikelyWindowFullscreen() {
const tolerance = 48; // Tolerance for taskbars, window borders and small variations
const matchesOuterScreen =
window.outerWidth >= (screen.width - tolerance) &&
window.outerHeight >= (screen.height - tolerance);
const matchesOuterAvail =
window.outerWidth >= (screen.availWidth - tolerance) &&
window.outerHeight >= (screen.availHeight - tolerance);
const matchesInnerAvail =
window.innerWidth >= (screen.availWidth - tolerance) &&
window.innerHeight >= (screen.availHeight - tolerance);
const browserChromeHeight = window.outerHeight - window.innerHeight;
const browserChromeWidth = window.outerWidth - window.innerWidth;
const minimalBrowserChrome = browserChromeHeight < 72 && browserChromeWidth < 72;
return (matchesOuterScreen || matchesOuterAvail || matchesInnerAvail) && minimalBrowserChrome;
}
// shared utilities moved from listing script
function createJumpKeyButton(options = {}) {
// Disabled: return an inert, non-interactive placeholder to avoid inserting the Watch Later UI
const placeholder = document.createElement('span');
placeholder.className = 'jumpkey-btn-deprecated';
placeholder.style.display = 'none';
return placeholder;
}
function getVideoIdFromElement(el) {
if (!el) return null;
// 1) direct anchors inside the thumb
const linkSelectors = ['a#thumbnail', 'a#video-title', 'a[href*="/watch" i]', 'a[href*="/shorts" i]', 'a.yt-simple-endpoint'];
for (const sel of linkSelectors) {
const anchor = el.querySelector(sel) || el.closest('ytd-video-renderer')?.querySelector(sel);
if (anchor) {
const href = anchor.href || anchor.getAttribute && anchor.getAttribute('href');
if (href) {
const abs = href.startsWith('/') ? (window.location.origin + href) : href;
const m = abs.match(/[?&]v=([^&]+)/) || abs.match(/\/shorts\/([^/?]+)/);
if (m && m[1]) return m[1];
}
}
}
// 2) data attributes on elements (many renderers include data-video-id)
const dataVid = el.querySelector('[data-video-id]')?.getAttribute('data-video-id') || el.getAttribute('data-video-id') || el.dataset?.videoId;
if (dataVid) return dataVid;
// 3) try to find any anchor ancestor with a href containing watch or shorts
const anc = el.closest && el.closest('a[href*="/watch" i], a[href*="/shorts" i]');
if (anc) {
const href = anc.href || anc.getAttribute('href');
if (href) {
const abs = href.startsWith('/') ? (window.location.origin + href) : href;
const m = abs.match(/[?&]v=([^&]+)/) || abs.match(/\/shorts\/([^/?]+)/);
if (m && m[1]) return m[1];
}
}
// 4) fallback: look for 'href' attributes inside the thumb text nodes
const anyAnchor = el.querySelector('a[href]');
if (anyAnchor) {
const href = anyAnchor.href || anyAnchor.getAttribute('href');
if (href) {
const abs = href.startsWith('/') ? (window.location.origin + href) : href;
const m = abs.match(/[?&]v=([^&]+)/) || abs.match(/\/shorts\/([^/?]+)/);
if (m && m[1]) return m[1];
}
}
return null;
}
function safeSendMessage(msg, cb) {
try {