-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1206 lines (1038 loc) · 42 KB
/
Copy pathcontent.js
File metadata and controls
1206 lines (1038 loc) · 42 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
console.log('[Watch Later Ext] INITIALIZED version 1.6 (Direct DOM checks)');
let watchLaterIds = new Set();
let lastInteractedVideoId = null;
function parseYtInitialData(html) {
const index = html.indexOf('ytInitialData');
if (index === -1) return null;
const start = html.indexOf('{', index);
if (start === -1) return null;
let braces = 1;
let end = start + 1;
while (braces > 0 && end < html.length) {
const char = html[end];
if (char === '{') braces++;
else if (char === '}') braces--;
end++;
}
if (braces === 0) {
const jsonStr = html.substring(start, end);
try {
return JSON.parse(jsonStr);
} catch (e) {
console.error('[Watch Later Ext] Failed to parse extracted JSON:', e);
}
}
return null;
}
async function fetchWatchLaterVideoIds() {
try {
const response = await fetch('https://www.youtube.com/playlist?list=WL');
const html = await response.text();
const data = parseYtInitialData(html);
if (!data) {
console.error('[Watch Later Ext] Could not find or parse ytInitialData in HTML.');
return new Set();
}
const videoIds = new Set();
function findVideoIds(obj) {
if (!obj || typeof obj !== 'object') return;
if (obj.playlistVideoRenderer && obj.playlistVideoRenderer.videoId) {
videoIds.add(obj.playlistVideoRenderer.videoId);
return;
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
findVideoIds(obj[key]);
}
}
}
findVideoIds(data);
return videoIds;
} catch (e) {
console.error('[Watch Later Ext] Error fetching watch later IDs:', e);
return new Set();
}
}
function saveWatchLaterIdsToStorage() {
chrome.storage.local.set({
watchLaterIds: Array.from(watchLaterIds),
lastFetchedTime: Date.now()
});
}
// Read ytcfg data by scanning already-loaded <script> tags (no new code execution, CSP-safe)
// Result is cached so we only scan once per page
let _pageConfigCache = null;
function getPageConfig() {
if (_pageConfigCache) return _pageConfigCache;
try {
const scripts = document.querySelectorAll('script');
for (const script of scripts) {
const text = script.textContent || '';
if (!text.includes('INNERTUBE_API_KEY')) continue;
const apiKeyMatch = text.match(/"INNERTUBE_API_KEY"\s*:\s*"([^"]+)"/);
const clientVerMatch = text.match(/"clientVersion"\s*:\s*"([^"]+)"/);
const clientNameMatch = text.match(/"clientName"\s*:\s*"([^"]+)"/);
const visitorMatch = text.match(/"VISITOR_DATA"\s*:\s*"([^"]+)"/);
if (apiKeyMatch) {
_pageConfigCache = {
apiKey: apiKeyMatch[1],
visitorData: visitorMatch ? visitorMatch[1] : null,
context: {
client: {
clientName: (clientNameMatch && clientNameMatch[1]) || 'WEB',
clientVersion: (clientVerMatch && clientVerMatch[1]) || '2.20260722.01.00'
}
}
};
return _pageConfigCache;
}
}
} catch (e) {
console.warn('[Watch Later Ext] Error reading page config from script tags:', e);
}
return {};
}
async function getSapisidHash() {
// Try both cookie names YouTube uses
const cookieNames = ['__Secure-3PAPISID', 'SAPISID'];
let sapisid = null;
for (const name of cookieNames) {
const match = document.cookie.match(new RegExp('(?:^|;)\\s*' + name + '=([^;]+)'));
if (match) { sapisid = match[1]; break; }
}
if (!sapisid) return null;
const timestamp = Math.floor(Date.now() / 1000);
const message = `${timestamp} ${sapisid} https://www.youtube.com`;
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer);
const hashHex = Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');
return `${timestamp}_${hashHex}`;
}
async function removeFromWatchLaterViaApi(videoId) {
if (!videoId) return false;
try {
// getPageConfig is now synchronous (reads existing script tags, no CSP issue)
const cfg = getPageConfig();
const sapisidHash = await getSapisidHash();
if (!sapisidHash) {
console.error('[Watch Later Ext] Could not compute SAPISIDHASH — user may not be logged in.');
return false;
}
const apiKey = cfg.apiKey;
if (!apiKey) {
console.error('[Watch Later Ext] Could not read API key from YouTube page config. Aborting.');
return false;
}
const context = cfg.context || { client: { clientName: 'WEB', clientVersion: 'unknown' } };
const clientVersion = context.client?.clientVersion || 'unknown';
console.log(`[Watch Later Ext] Calling edit_playlist API (REMOVE). apiKey: ${apiKey.slice(0,8)}..., clientVersion: ${clientVersion}`);
const response = await fetch(
`https://www.youtube.com/youtubei/v1/browse/edit_playlist?key=${apiKey}&prettyPrint=false`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `SAPISIDHASH ${sapisidHash}`,
'X-Origin': 'https://www.youtube.com',
'X-Goog-AuthUser': '0',
'X-Youtube-Client-Name': '1',
'X-Youtube-Client-Version': clientVersion,
},
body: JSON.stringify({
playlistId: 'WL',
actions: [{ action: 'ACTION_REMOVE_VIDEO_BY_VIDEO_ID', removedVideoId: videoId }],
context: context
})
}
);
if (response.ok) {
console.log(`[Watch Later Ext] ✓ Removed video "${videoId}" from Watch Later via API.`);
return true;
} else {
const txt = await response.text();
console.error(`[Watch Later Ext] API removal failed (${response.status}):`, txt.slice(0, 300));
return false;
}
} catch (e) {
console.error('[Watch Later Ext] Error calling removal API:', e);
return false;
}
}
async function addToWatchLaterViaApi(videoId) {
if (!videoId) return false;
try {
const cfg = getPageConfig();
const sapisidHash = await getSapisidHash();
if (!sapisidHash) {
console.error('[Watch Later Ext] Could not compute SAPISIDHASH — user may not be logged in.');
return false;
}
const apiKey = cfg.apiKey;
if (!apiKey) {
console.error('[Watch Later Ext] Could not read API key from YouTube page config. Aborting.');
return false;
}
const context = cfg.context || { client: { clientName: 'WEB', clientVersion: 'unknown' } };
const clientVersion = context.client?.clientVersion || 'unknown';
console.log(`[Watch Later Ext] Calling edit_playlist API (ADD). apiKey: ${apiKey.slice(0,8)}..., clientVersion: ${clientVersion}`);
const response = await fetch(
`https://www.youtube.com/youtubei/v1/browse/edit_playlist?key=${apiKey}&prettyPrint=false`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `SAPISIDHASH ${sapisidHash}`,
'X-Origin': 'https://www.youtube.com',
'X-Goog-AuthUser': '0',
'X-Youtube-Client-Name': '1',
'X-Youtube-Client-Version': clientVersion,
},
body: JSON.stringify({
playlistId: 'WL',
actions: [{ action: 'ACTION_ADD_VIDEO', addedVideoId: videoId }],
context: context
})
}
);
if (response.ok) {
console.log(`[Watch Later Ext] ✓ Added video "${videoId}" to Watch Later via API.`);
return true;
} else {
const txt = await response.text();
console.error(`[Watch Later Ext] API add failed (${response.status}):`, txt.slice(0, 300));
return false;
}
} catch (e) {
console.error('[Watch Later Ext] Error calling add API:', e);
return false;
}
}
function initWatchLaterCache() {
chrome.storage.local.get(['watchLaterIds', 'lastFetchedTime'], async (result) => {
const now = Date.now();
let cacheValid = false;
if (result.watchLaterIds && result.lastFetchedTime) {
// 1 hour cache validation
if (now - result.lastFetchedTime < 60 * 60 * 1000) {
watchLaterIds = new Set(result.watchLaterIds);
cacheValid = true;
console.log(`[Watch Later Ext] Loaded ${watchLaterIds.size} video IDs from storage cache.`);
updateAllButtonsState();
}
}
if (!cacheValid) {
console.log('[Watch Later Ext] Cache invalid or missing. Fetching fresh Watch Later IDs...');
const freshIds = await fetchWatchLaterVideoIds();
watchLaterIds = freshIds;
console.log(`[Watch Later Ext] Fetched ${watchLaterIds.size} fresh video IDs from YouTube.`);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
}
});
}
// Sync changes from other tabs in real-time
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local' && changes.watchLaterIds) {
watchLaterIds = new Set(changes.watchLaterIds.newValue || []);
console.log(`[Watch Later Ext] Storage changed. Loaded ${watchLaterIds.size} video IDs.`);
updateAllButtonsState();
}
});
function findDeepLink(el) {
if (!el) return null;
if (el.tagName === 'A') {
const href = el.getAttribute('href');
if (href && href.includes('watch?v=')) {
return href;
}
}
if (el.children) {
for (const child of el.children) {
const found = findDeepLink(child);
if (found) return found;
}
}
if (el.shadowRoot && el.shadowRoot.children) {
for (const child of el.shadowRoot.children) {
const found = findDeepLink(child);
if (found) return found;
}
}
return null;
}
function findNativeOverlayButton(el) {
if (!el) return null;
const tag = el.tagName ? el.tagName.toUpperCase() : '';
if (tag === 'YTD-THUMBNAIL-OVERLAY-TOGGLE-BUTTON-RENDERER' || tag === 'YT-THUMBNAIL-OVERLAY-TOGGLE-BUTTON-RENDERER') {
const label = (el.getAttribute('aria-label') || '').toLowerCase();
const isWatchLater = label.includes('watch later') || label.includes('צפייה מאוחרת') || label.includes('לצפייה מאוחרת');
if (isWatchLater) {
return el;
}
}
if (el.children) {
for (const child of el.children) {
const found = findNativeOverlayButton(child);
if (found) return found;
}
}
if (el.shadowRoot && el.shadowRoot.children) {
for (const child of el.shadowRoot.children) {
const found = findNativeOverlayButton(child);
if (found) return found;
}
}
return null;
}
function clickNativeOverlayButton(videoEl, actionType) {
const overlay = findNativeOverlayButton(videoEl);
if (overlay) {
const label = (overlay.getAttribute('aria-label') || '').toLowerCase();
const isAlreadyAdded = label.includes('remove') || label.includes('הסר') || label.includes('הסרה');
console.log(`[Watch Later Ext] Found native overlay button:`, overlay, `Label: "${label}", isAlreadyAdded: ${isAlreadyAdded}, actionType: "${actionType}"`);
if (actionType === 'add' && !isAlreadyAdded) {
overlay.click();
console.log('[Watch Later Ext] Clicked native overlay button to ADD.');
return true;
} else if (actionType === 'remove' && isAlreadyAdded) {
overlay.click();
console.log('[Watch Later Ext] Clicked native overlay button to REMOVE.');
return true;
} else {
console.log('[Watch Later Ext] Native overlay button is already in desired state.');
return true;
}
}
return false;
}
function getVideoId(videoEl) {
if (!videoEl) return null;
if (videoEl.data && videoEl.data.videoId) {
return videoEl.data.videoId;
}
if (videoEl.videoId) {
return videoEl.videoId;
}
// Look for any link with watch?v=
const links = videoEl.querySelectorAll('a[href*="watch?v="]');
for (const link of links) {
const href = link.getAttribute('href');
if (href) {
const match = href.match(/[?&]v=([^&#]+)/);
if (match) {
return match[1];
}
}
}
// Shadow DOM fallback
const deepLink = findDeepLink(videoEl);
if (deepLink) {
const match = deepLink.match(/[?&]v=([^&#]+)/);
if (match) {
return match[1];
}
}
return null;
}
function getCurrentPlayerVideoId(player) {
// 1. From ytd-watch-flexy / ytd-watch-grid attribute
const watchFlexy = document.querySelector('ytd-watch-flexy, ytd-watch-grid');
if (watchFlexy) {
const vId = watchFlexy.getAttribute('video-id');
if (vId) return vId;
}
// 2. From URL params if on /watch
const urlParams = new URLSearchParams(window.location.search);
const urlVid = urlParams.get('v');
if (urlVid) return urlVid;
// 3. From player title link if present
if (player) {
const titleLink = player.querySelector('a.ytp-title-link');
if (titleLink && titleLink.href) {
const match = titleLink.href.match(/[?&]v=([^&#]+)/);
if (match) return match[1];
}
}
// 4. From meta tag
const metaVid = document.querySelector('meta[itemprop="videoId"]');
if (metaVid && metaVid.content) return metaVid.content;
// 5. From shorts URL if /shorts/ID
if (window.location.pathname.startsWith('/shorts/')) {
const parts = window.location.pathname.split('/');
if (parts[2]) return parts[2];
}
return null;
}
function updateButtonState(btn, isSaved) {
if (isSaved) {
btn.classList.add('wl-state-added');
btn.title = "Remove from Watch Later";
btn.setAttribute('aria-label', 'Remove from Watch Later');
} else {
btn.classList.remove('wl-state-added');
btn.title = "Add to Watch Later";
btn.setAttribute('aria-label', 'Add to Watch Later');
}
}
function updateAllButtonsState() {
const btns = document.querySelectorAll('.wl-custom-add-btn');
btns.forEach(btn => {
if (btn.classList.contains('wl-just-removed')) return;
if (btn.classList.contains('wl-player-btn')) {
const player = btn.closest('.html5-video-player, #movie_player');
const videoId = getCurrentPlayerVideoId(player);
if (videoId) {
const isSaved = watchLaterIds.has(videoId);
updateButtonState(btn, isSaved);
}
return;
}
const videoEl = btn.closest(
'ytd-rich-item-renderer, ytd-video-renderer, ytd-compact-video-renderer, ytd-grid-video-renderer, yt-lockup-view-model'
);
if (!videoEl) return;
const videoId = getVideoId(videoEl);
if (videoId) {
const isSaved = watchLaterIds.has(videoId);
updateButtonState(btn, isSaved);
}
});
}
function injectButtons() {
// Only run on the Watch Later playlist page
if (!window.location.href.includes('list=WL')) return;
const videos = document.querySelectorAll('ytd-playlist-video-renderer, ytd-playlist-panel-video-renderer');
videos.forEach(video => {
// Check if we already added the button to this video
if (video.querySelector('.wl-custom-remove-btn')) return;
const menuContainer = video.querySelector('#menu');
if (!menuContainer) return;
const btn = document.createElement('button');
btn.className = 'wl-custom-remove-btn';
// SVG icon for a trash can
btn.innerHTML = `
<svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false">
<g>
<path d="M11 17H9V8h2v9zm4-9h-2v9h2V8zm4-4v1h-1v16H6V5H5V4h4V3h6v1h4zm-2 1H7v15h10V5z"></path>
</g>
</svg>
`;
btn.title = "1-Click Remove from Watch Later";
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const videoId = getVideoId(video);
// Optimistic: animate the row out immediately — feels instant
video.style.transition = 'opacity 0.18s ease, transform 0.18s ease';
video.style.opacity = '0';
video.style.transform = 'translateX(-12px)';
const removeTimer = setTimeout(() => video.remove(), 200);
if (videoId) {
watchLaterIds.delete(videoId);
saveWatchLaterIdsToStorage();
}
// Fire API in background — if it fails, restore the row
removeFromWatchLaterViaApi(videoId).then(success => {
if (!success) {
console.warn('[Watch Later Ext] API removal failed for trash btn, row will stay removed from local cache.');
// Row is already gone from DOM — just clear the timer to be safe
clearTimeout(removeTimer);
}
});
});
// Insert our button before the existing menu button so it appears to the left of the 3 dots
menuContainer.insertBefore(btn, menuContainer.firstChild);
});
}
// Helper function to click the native "Remove from Watch later" option
function clickRemoveOption() {
return new Promise(resolve => {
let attempts = 0;
let foundItemsLog = [];
const interval = setInterval(() => {
attempts++;
const items = document.querySelectorAll('ytd-menu-service-item-renderer, ytd-menu-navigation-item-renderer, tp-yt-paper-item');
for (const item of items) {
if (item.getBoundingClientRect().height === 0) continue;
const text = item.textContent.replace(/\s+/g, ' ').trim().toLowerCase();
const html = item.innerHTML;
if (text && !foundItemsLog.includes(text)) {
foundItemsLog.push(text);
}
const isRemove = text.includes('remove from') ||
(text.includes('remove') && text.includes('watch later')) ||
html.includes('M11 17H9V8h2v9zm4-9h-2v9h2V8zm4-4v1h-1v16H6V5H5V4h4V3h6v1h4zm-2 1H7v15h10V5z');
if (isRemove) {
item.click();
item.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
item.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
clearInterval(interval);
resolve(true);
return;
}
}
if (attempts > 50) {
clearInterval(interval);
console.error('Watch Later Extension: Could not find the remove option. Available visible menu items were:', foundItemsLog);
resolve(false);
}
}, 50);
});
}
function injectAddButtons() {
// Don't inject on the dedicated Watch Later playlist page (/playlist?list=WL)
// but DO inject on watch pages even if list=WL is in the URL
const url = new URL(window.location.href);
if (url.pathname === '/playlist' && url.searchParams.get('list') === 'WL') return;
const videos = document.querySelectorAll(
'ytd-rich-item-renderer, ytd-video-renderer, ytd-compact-video-renderer, ytd-grid-video-renderer, yt-lockup-view-model'
);
videos.forEach(video => {
if (video.tagName.toLowerCase() === 'yt-lockup-view-model' &&
video.parentElement.closest('ytd-rich-item-renderer, ytd-video-renderer, ytd-compact-video-renderer, ytd-grid-video-renderer')) {
return;
}
if (video.querySelector('.wl-custom-add-btn')) return;
let menuContainer = video.querySelector('.ytLockupMetadataViewModelMenuButton') ||
video.querySelector('[class*="MenuButton"]') ||
video.querySelector('#menu') ||
video.querySelector('ytd-menu-renderer');
if (!menuContainer) return;
const btn = document.createElement('button');
btn.className = 'wl-custom-add-btn';
btn.innerHTML = `
<!-- Clock/Plus icon (Default) -->
<svg class="wl-icon-add" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" style="width:24px;height:24px;">
<g><path d="M14.97 16.95 10 13.87V7h2v5.76l4.03 2.49-1.06 1.7zM12 3c-4.96 0-9 4.04-9 9s4.04 9 9 9 9-4.04 9-9-4.04-9-9-9m0-1c5.52 0 10 4.48 10 10s-4.48 10-10 10S2 17.52 2 12 6.48 2 12 2z"></path></g>
</svg>
<!-- Green Checkmark icon -->
<svg class="wl-icon-check" viewBox="0 0 24 24" style="width:24px;height:24px;">
<g><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path></g>
</svg>
<!-- Red X icon -->
<svg class="wl-icon-remove" viewBox="0 0 24 24" style="width:24px;height:24px;">
<g><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path></g>
</svg>
`;
const videoId = getVideoId(video);
const isSaved = videoId ? watchLaterIds.has(videoId) : false;
updateButtonState(btn, isSaved);
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const videoEl = btn.closest(
'ytd-rich-item-renderer, ytd-video-renderer, ytd-compact-video-renderer, ytd-grid-video-renderer, yt-lockup-view-model'
);
if (!videoEl) return;
const currentVideoId = getVideoId(videoEl);
const isAdded = btn.classList.contains('wl-state-added');
const actionType = isAdded ? 'remove' : 'add';
if (actionType === 'remove' && currentVideoId) {
// --- OPTIMISTIC REMOVE: flip state instantly, API in background ---
updateButtonState(btn, false);
btn.classList.add('wl-just-removed');
watchLaterIds.delete(currentVideoId);
saveWatchLaterIdsToStorage();
videoEl.addEventListener('mouseleave', function reset() {
btn.classList.remove('wl-just-removed');
videoEl.removeEventListener('mouseleave', reset);
});
removeFromWatchLaterViaApi(currentVideoId).then(success => {
if (!success) {
// Revert if API failed
console.warn('[Watch Later Ext] API remove failed, reverting button state.');
updateButtonState(btn, true);
btn.classList.remove('wl-just-removed');
watchLaterIds.add(currentVideoId);
saveWatchLaterIdsToStorage();
}
});
return;
}
// --- ADD path: optimistic update + API with fallback to UI automation ---
updateButtonState(btn, true);
watchLaterIds.add(currentVideoId);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
addToWatchLaterViaApi(currentVideoId).then(async (success) => {
if (!success) {
console.warn('[Watch Later Ext] API add failed, attempting UI automation fallback...');
let status = 'failed';
const usedOverlay = clickNativeOverlayButton(videoEl, actionType);
if (usedOverlay) {
status = 'added';
} else {
let triggerBtn = videoEl.querySelector('.ytLockupMetadataViewModelMenuButton button-view-model button') ||
videoEl.querySelector('.ytLockupMetadataViewModelMenuButton button') ||
videoEl.querySelector('button[aria-haspopup="true"], button[aria-haspopup="menu"]') ||
videoEl.querySelector('ytd-menu-renderer yt-icon-button#button button') ||
videoEl.querySelector('ytd-menu-renderer button');
if (triggerBtn) {
const popupContainer = document.querySelector('ytd-popup-container');
if (popupContainer) {
popupContainer.style.opacity = '0';
popupContainer.style.pointerEvents = 'none';
}
triggerBtn.click();
status = await clickOption(actionType);
if (popupContainer) {
popupContainer.style.opacity = '';
popupContainer.style.pointerEvents = '';
}
}
}
if (status === 'failed') {
document.body.click();
console.warn('[Watch Later Ext] Fallback UI add failed, reverting state.');
updateButtonState(btn, false);
watchLaterIds.delete(currentVideoId);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
}
}
});
});
menuContainer.appendChild(btn);
});
}
function injectPlayerButton() {
const rightControlsList = document.querySelectorAll(
'.html5-video-player .ytp-right-controls, #movie_player .ytp-right-controls'
);
rightControlsList.forEach(rightControls => {
const player = rightControls.closest('.html5-video-player, #movie_player');
const currentVideoId = getCurrentPlayerVideoId(player);
let btn = rightControls.querySelector('.wl-player-btn');
if (!btn) {
btn = document.createElement('button');
btn.className = 'ytp-button wl-player-btn wl-custom-add-btn';
btn.setAttribute('aria-label', 'Add to Watch Later');
btn.innerHTML = `
<!-- Clock/Plus icon (Default) -->
<svg class="wl-icon-add" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false">
<g><path d="M14.97 16.95 10 13.87V7h2v5.76l4.03 2.49-1.06 1.7zM12 3c-4.96 0-9 4.04-9 9s4.04 9 9 9 9-4.04 9-9-4.04-9-9-9m0-1c5.52 0 10 4.48 10 10s-4.48 10-10 10S2 17.52 2 12 6.48 2 12 2z"></path></g>
</svg>
<!-- Green Checkmark icon -->
<svg class="wl-icon-check" viewBox="0 0 24 24">
<g><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path></g>
</svg>
<!-- Red X icon -->
<svg class="wl-icon-remove" viewBox="0 0 24 24">
<g><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path></g>
</svg>
`;
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const curPlayer = btn.closest('.html5-video-player, #movie_player');
const videoId = getCurrentPlayerVideoId(curPlayer);
if (!videoId) {
console.warn('[Watch Later Ext] Could not determine video ID for player button click.');
return;
}
const isAdded = btn.classList.contains('wl-state-added');
const actionType = isAdded ? 'remove' : 'add';
if (actionType === 'remove') {
// Optimistic remove
updateButtonState(btn, false);
btn.classList.add('wl-just-removed');
watchLaterIds.delete(videoId);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
btn.addEventListener('mouseleave', function reset() {
btn.classList.remove('wl-just-removed');
btn.removeEventListener('mouseleave', reset);
});
setTimeout(() => btn.classList.remove('wl-just-removed'), 1000);
removeFromWatchLaterViaApi(videoId).then(success => {
if (!success) {
console.warn('[Watch Later Ext] API remove failed for player button, reverting state.');
updateButtonState(btn, true);
btn.classList.remove('wl-just-removed');
watchLaterIds.add(videoId);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
}
});
} else {
// Optimistic add
updateButtonState(btn, true);
watchLaterIds.add(videoId);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
addToWatchLaterViaApi(videoId).then(success => {
if (!success) {
console.warn('[Watch Later Ext] API add failed for player button, reverting state.');
updateButtonState(btn, false);
watchLaterIds.delete(videoId);
saveWatchLaterIdsToStorage();
updateAllButtonsState();
}
});
}
});
// Insert at the beginning of right controls (before CC / Settings)
rightControls.insertBefore(btn, rightControls.firstChild);
}
if (currentVideoId) {
const isSaved = watchLaterIds.has(currentVideoId);
updateButtonState(btn, isSaved);
}
});
}
function clickOption(actionType) {
console.log(`[Watch Later Ext] clickOption starting with actionType: "${actionType}"`);
const popupContainer = document.querySelector('ytd-popup-container');
if (popupContainer) {
popupContainer.classList.add('wl-hide-popup');
}
return new Promise(resolve => {
let attempts = 0;
const interval = setInterval(async () => {
attempts++;
let items = [];
if (popupContainer) {
items.push(...popupContainer.querySelectorAll(
'ytd-menu-service-item-renderer, ytd-menu-navigation-item-renderer, ' +
'tp-yt-paper-item, yt-list-item-view-model, ' +
'ytd-menu-popup-renderer tp-yt-paper-listbox > *'
));
}
document.querySelectorAll('tp-yt-iron-dropdown:not([aria-hidden="true"]), iron-dropdown:not([aria-hidden="true"])').forEach(d => {
items.push(...d.querySelectorAll('*'));
});
document.querySelectorAll('ytd-menu-popup-renderer').forEach(r => {
items.push(...r.querySelectorAll('tp-yt-paper-item, ytd-menu-service-item-renderer, a, [role="menuitem"], [role="option"]'));
});
items = [...new Set(items)];
if (actionType === 'add') {
for (const item of items) {
const rect = item.getBoundingClientRect();
if (rect.height === 0 || rect.width === 0) continue;
const text = item.textContent.replace(/\s+/g, ' ').trim().toLowerCase();
if (!text) continue;
const paths = Array.from(item.querySelectorAll('path')).map(p => p.getAttribute('d') || '');
const hasClockIcon = paths.some(d => d.includes('14.97') && d.includes('16.95') && d.includes('13.87'));
const isWatchLater = text.includes('save to watch later') ||
text.includes('add to watch later') ||
text.includes('watch later') ||
text.includes('צפייה מאוחרת') ||
text.includes('לצפייה מאוחרת') ||
hasClockIcon;
if (isWatchLater) {
console.log(`[Watch Later Ext] Found direct Watch Later option: "${text}"`);
item.click();
clearInterval(interval);
if (popupContainer) {
popupContainer.classList.remove('wl-hide-popup');
}
resolve('added');
return;
}
}
} else if (actionType === 'remove') {
for (const item of items) {
const rect = item.getBoundingClientRect();
if (rect.height === 0 || rect.width === 0) continue;
const text = item.textContent.replace(/\s+/g, ' ').trim().toLowerCase();
if (!text) continue;
const isSaveToPlaylist = text.includes('save to playlist') ||
text === 'save' ||
text.includes('שמירה לרשימת השמעה') ||
text === 'שמירה' ||
text.includes('שמירה לרשימה');
if (isSaveToPlaylist) {
console.log(`[Watch Later Ext] Found Save to Playlist option: "${text}". Opening dialog...`);
const dialogObserver = new MutationObserver((mutations, observerInstance) => {
const renderer = findDialogRenderer();
if (renderer) {
renderer.classList.add('wl-hide-dialog');
const parentDialog = findClosestDialogParent(renderer);
if (parentDialog) {
parentDialog.classList.add('wl-hide-dialog');
}
observerInstance.disconnect();
}
});
dialogObserver.observe(document.body, { childList: true, subtree: true });
item.click();
clearInterval(interval);
const success = await uncheckWatchLaterInDialog();
if (popupContainer) {
popupContainer.classList.remove('wl-hide-popup');
}
resolve(success ? 'removed' : 'failed');
return;
}
}
}
if (attempts > 60) {
clearInterval(interval);
console.error('[Watch Later Ext] Timeout: Could not find menu item.');
document.body.click();
if (popupContainer) {
popupContainer.classList.remove('wl-hide-popup');
}
resolve('failed');
}
}, 50);
});
}
function deepQuerySelector(selector, root = document) {
if (!root) return null;
const found = root.querySelector(selector);
if (found) return found;
if (root.children) {
for (const child of root.children) {
const res = deepQuerySelector(selector, child);
if (res) return res;
}
}
if (root.shadowRoot) {
const res = deepQuerySelector(selector, root.shadowRoot);
if (res) return res;
}
return null;
}
function deepQuerySelectorAll(selector, root = document, results = []) {
if (!root) return results;
const elements = root.querySelectorAll(selector);
for (const el of elements) {
if (!results.includes(el)) {
results.push(el);
}
}
if (root.children) {
for (const child of root.children) {
deepQuerySelectorAll(selector, child, results);
}
}
if (root.shadowRoot) {
deepQuerySelectorAll(selector, root.shadowRoot, results);
}
return results;
}
function findClosestDialogParent(el) {
if (!el) return null;
const closest = el.closest ? el.closest('tp-yt-paper-dialog, dialog, [role="dialog"]') : null;
if (closest) return closest;
let parent = el.parentNode;
if (!parent && el.getRootNode) {
const root = el.getRootNode();
if (root && root.host) {
parent = root.host;
}
}
if (parent) {
return findClosestDialogParent(parent);
}
return null;
}
function findDialogRenderer() {
const popup = document.querySelector('ytd-popup-container');
if (popup) {
const el = deepQuerySelector('ytd-add-to-playlist-renderer, yt-add-to-playlist-renderer', popup);
if (el) return el;
}
return deepQuerySelector('ytd-add-to-playlist-renderer, yt-add-to-playlist-renderer', document.body);
}
function findCloseButton(renderer) {
if (!renderer) return null;
const selectors = ['yt-icon-button#close-button', 'button[aria-label="Close"]', 'button#close-button', '[id*="close"]', '[class*="close"]'];
for (const sel of selectors) {
const btn = deepQuerySelector(sel, renderer);
if (btn) return btn;
}
const allBtns = deepQuerySelectorAll('button, yt-icon-button, paper-button', renderer);
for (const b of allBtns) {
const id = b.id || '';
const label = b.getAttribute('aria-label') || '';
const text = b.textContent || '';
if (id.toLowerCase().includes('close') ||
label.toLowerCase().includes('close') ||
label.toLowerCase().includes('סגור') ||
text.toLowerCase().includes('close') ||
text.toLowerCase().includes('סגור')) {
return b;
}
}
return null;
}