-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
4409 lines (4120 loc) · 217 KB
/
main.js
File metadata and controls
4409 lines (4120 loc) · 217 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
'use strict';
const {
app, BrowserWindow, BrowserView,
ipcMain, dialog, shell, session, Menu, clipboard,
} = require('electron');
const path = require('path');
const fs = require('fs');
const https = require('https');
const { spawn } = require('child_process');
const { pathToFileURL } = require('url');
const os = require('os');
const { shouldBlock } = require('./blocklist.js');
// Domains never blocked regardless of settings (needed for site functionality)
const BUILTIN_WHITELIST = [
// TikTok — only core content/video delivery domains; tracker subdomains are NOT listed
// so they can be blocked by shouldBlock() normally.
'tiktok.com','tiktokv.com','tiktokcdn.com','tiktokcdn-us.com','ttwstatic.com',
'ibytedtos.com','ibyteimg.com','byteoversea.com',
// Spotify — CDN, auth, and DRM license domains required for playback
'spotify.com','scdn.co','spotifycdn.com','spotifycdn.net',
'pscdn.co','spotilocal.com','audio-ak-spotify-com.akamaized.net',
// Google — ALL auth, sign-in, and service domains must preserve headers intact.
// Google's OAuth flow validates Referer, Sec-Fetch-*, and other headers across
// redirects between these domains. Any stripping triggers the
// "This browser may not be secure" block on accounts.google.com.
'google.com','accounts.google.com','apis.google.com',
'googleapis.com','googleusercontent.com','gstatic.com',
'gmail.com','youtube.com','ytimg.com','ggpht.com',
// NOTE: google-analytics.com and googletagmanager.com intentionally NOT listed here
// so they remain blockable by shouldBlock(). They don't affect Google auth flows.
];
// Tracker/analytics subdomains that must be blocked even if their parent domain
// is in BUILTIN_WHITELIST. These take priority over the whitelist.
const TRACKER_FORCE_BLOCK = new Set([
// TikTok analytics, logging, monitoring, and ad infrastructure
'analytics.tiktok.com', 'log.tiktok.com', 'log-va.tiktok.com',
'log-sg.tiktok.com', 'log-useast2a.tiktok.com', 'log-useast8.tiktok.com',
'mon.tiktok.com', 'stats.tiktok.com', 'event.tiktok.com',
'metrics.tiktok.com', 'monitor.tiktok.com', 'tracker.tiktok.com',
'ads.tiktok.com', 'business.tiktok.com',
// ByteDance tracking SDK and analytics infrastructure (not needed for playback)
'snssdk.com', 'bdurl.net', 'musical.ly',
'toblog.ctobsnssdk.com', 'lf16-tiktok-web.tiktokcdn.com',
// Google tracker subdomains — force-block even though googleapis.com/gstatic.com
// are in BUILTIN_WHITELIST for auth. These subdomains carry no auth traffic.
'imasdk.googleapis.com',
'pagead2.googlesyndication.com', 'tpc.googlesyndication.com',
'stats.g.doubleclick.net', 'cm.g.doubleclick.net',
'fundingchoicesmessages.google.com',
'adservice.google.com',
'ssl.google-analytics.com', 'analytics.google.com',
'csi.gstatic.com',
]);
if (process.platform === 'win32') app.setAppUserModelId('com.raw.browser');
// Remove the automation flag Electron sets by default — Google checks this
// to determine if the browser is automated/non-standard. Must be set before
// any window is created (commandLine switches are read at startup).
app.commandLine.appendSwitch('disable-blink-features', 'AutomationControlled');
// ── ENHANCED PRIVACY: Prevent IP leaks through WebRTC ───────────────────────
app.commandLine.appendSwitch('disable-webrtc-ip-handling');
app.commandLine.appendSwitch('force-webrtc-ip-handling-policy', 'default_public_interface_only');
app.commandLine.appendSwitch('webrtc-ip-handling-policy', 'disable_non_proxied_udp');
// Disable geolocation, microphone, camera by default
app.commandLine.appendSwitch('disable-geolocation');
app.commandLine.appendSwitch('disable-web-notifications');
// ── Widevine CDM (enables DRM for Spotify, Netflix, etc.) ─────────────────────
(function tryLoadWidevine() {
function _tryDir(base) {
// base is e.g. Chrome's or Edge's "Application" folder
if (!fs.existsSync(base)) return false;
const versions = fs.readdirSync(base)
.filter(v => /^\d+\.\d+\.\d+\.\d+$/.test(v))
.sort((a, b) => {
const pa = a.split('.').map(Number), pb = b.split('.').map(Number);
for (let i = 0; i < 4; i++) { if (pa[i] !== pb[i]) return pb[i] - pa[i]; }
return 0;
});
for (const ver of versions) {
const cdmPath = path.join(base, ver, 'WidevineCdm', '_platform_specific', 'win_x64', 'widevinecdm.dll');
const manifest = path.join(base, ver, 'WidevineCdm', 'manifest.json');
if (fs.existsSync(cdmPath) && fs.existsSync(manifest)) {
const mf = JSON.parse(fs.readFileSync(manifest, 'utf8'));
app.commandLine.appendSwitch('widevine-cdm-path', cdmPath);
app.commandLine.appendSwitch('widevine-cdm-version', mf.version || '');
return true;
}
}
return false;
}
function _tryUserDataDir(base) {
// Modern Chrome/Edge stores WidevineCdm under User Data\WidevineCdm\<version>\
// e.g. %LOCALAPPDATA%\Google\Chrome\User Data\WidevineCdm\4.10.2557.0\
if (!fs.existsSync(base)) return false;
const versions = fs.readdirSync(base)
.filter(v => /^\d+\.\d+\.\d+\.\d+$/.test(v))
.sort((a, b) => {
const pa = a.split('.').map(Number), pb = b.split('.').map(Number);
for (let i = 0; i < 4; i++) { if (pa[i] !== pb[i]) return pb[i] - pa[i]; }
return 0;
});
for (const ver of versions) {
const cdmPath = path.join(base, ver, '_platform_specific', 'win_x64', 'widevinecdm.dll');
const manifest = path.join(base, ver, 'manifest.json');
if (fs.existsSync(cdmPath) && fs.existsSync(manifest)) {
try {
const mf = JSON.parse(fs.readFileSync(manifest, 'utf8'));
app.commandLine.appendSwitch('widevine-cdm-path', cdmPath);
app.commandLine.appendSwitch('widevine-cdm-version', mf.version || ver);
return true;
} catch { return false; }
}
}
return false;
}
try {
if (process.platform === 'win32') {
const local = process.env.LOCALAPPDATA || '';
const prog = process.env.PROGRAMFILES || 'C:\\Program Files';
const prog86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';
// Modern Chrome/Edge/Brave (v120+) keeps WidevineCdm in User Data, not Application
const userDataCandidates = [
path.join(local, 'Google', 'Chrome', 'User Data', 'WidevineCdm'),
path.join(local, 'Microsoft', 'Edge', 'User Data', 'WidevineCdm'),
path.join(local, 'BraveSoftware', 'Brave-Browser', 'User Data', 'WidevineCdm'),
path.join(prog, 'Google', 'Chrome', 'User Data', 'WidevineCdm'),
];
let found = false;
for (const c of userDataCandidates) { if (_tryUserDataDir(c)) { found = true; break; } }
// Fallback: legacy Application\<ver>\WidevineCdm layout (older Chrome/Edge installs)
if (!found) {
const candidates = [
path.join(local, 'Google', 'Chrome', 'Application'),
path.join(local, 'Microsoft', 'Edge', 'Application'),
path.join(prog, 'Google', 'Chrome', 'Application'),
path.join(prog86, 'Google', 'Chrome', 'Application'),
path.join(prog, 'Microsoft', 'Edge', 'Application'),
];
for (const c of candidates) { if (_tryDir(c)) break; }
}
} else if (process.platform === 'darwin') {
// macOS: try Chrome (arm64 + x64), then Brave
const _tryMacCdm = (cdmPath, manifestPath) => {
if (!fs.existsSync(cdmPath) || !fs.existsSync(manifestPath)) return false;
try {
const mf = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
app.commandLine.appendSwitch('widevine-cdm-path', cdmPath);
app.commandLine.appendSwitch('widevine-cdm-version', mf.version || '');
return true;
} catch { return false; }
};
const _macBase = (app_name, fw_name) =>
`/Applications/${app_name}.app/Contents/Frameworks/${fw_name}.framework/Versions/Current/Libraries/WidevineCdm`;
const _macChromeBase = _macBase('Google Chrome', 'Google Chrome Framework');
const _macBraveBase = _macBase('Brave Browser', 'Brave Browser Framework');
[
[_macChromeBase + '/_platform_specific/mac_arm64/libwidevinecdm.dylib', _macChromeBase + '/manifest.json'],
[_macChromeBase + '/_platform_specific/mac_x64/libwidevinecdm.dylib', _macChromeBase + '/manifest.json'],
[_macBraveBase + '/_platform_specific/mac_arm64/libwidevinecdm.dylib', _macBraveBase + '/manifest.json'],
[_macBraveBase + '/_platform_specific/mac_x64/libwidevinecdm.dylib', _macBraveBase + '/manifest.json'],
].some(([cdm, mf]) => _tryMacCdm(cdm, mf));
} else if (process.platform === 'linux') {
// Linux: search versioned WidevineCdm dirs under Chrome/Chromium user + system paths
const home = process.env.HOME || '';
function _tryLinuxCdmDir(base) {
if (!fs.existsSync(base)) return false;
const versions = fs.readdirSync(base)
.filter(v => /^\d+\.\d+\.\d+\.\d+$/.test(v))
.sort((a, b) => {
const pa = a.split('.').map(Number), pb = b.split('.').map(Number);
for (let i = 0; i < 4; i++) { if (pa[i] !== pb[i]) return pb[i] - pa[i]; }
return 0;
});
for (const ver of versions) {
const cdmPath = path.join(base, ver, '_platform_specific', 'linux_x64', 'libwidevinecdm.so');
const manifest = path.join(base, ver, 'manifest.json');
if (fs.existsSync(cdmPath) && fs.existsSync(manifest)) {
try {
const mf = JSON.parse(fs.readFileSync(manifest, 'utf8'));
app.commandLine.appendSwitch('widevine-cdm-path', cdmPath);
app.commandLine.appendSwitch('widevine-cdm-version', mf.version || '');
return true;
} catch {}
}
}
return false;
}
const linuxCandidates = [
path.join(home, '.config', 'google-chrome', 'WidevineCdm'),
path.join(home, '.config', 'chromium', 'WidevineCdm'),
path.join(home, '.var', 'app', 'com.google.Chrome', 'config', 'google-chrome', 'WidevineCdm'),
path.join(home, '.var', 'app', 'org.chromium.Chromium', 'config', 'chromium', 'WidevineCdm'),
path.join(home, 'snap', 'google-chrome', 'current', '.config', 'google-chrome', 'WidevineCdm'),
'/opt/google/chrome/WidevineCdm',
'/usr/lib/chromium/WidevineCdm',
'/usr/lib/chromium-browser/WidevineCdm',
];
for (const c of linuxCandidates) { if (_tryLinuxCdmDir(c)) break; }
}
} catch { /* Widevine unavailable — silently continue */ }
})();
// Allow audio/video autoplay without user gesture (needed for Music Player)
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
// Prevent Chromium from EVER suspending background renderer processes or their media.
// This is the definitive fix for videos/audio pausing when a BV is detached from the window.
// JS-level overrides (visibility, blur, etc.) can race with native Chromium scheduler events;
// these flags disable the scheduler behaviour entirely at the process level.
app.commandLine.appendSwitch('disable-renderer-backgrounding');
app.commandLine.appendSwitch('disable-background-media-suspend');
// ── Default browser + external URL handling ──────────────────────────────────
// Register RAW as a capable handler for http/https at the OS level.
// On Windows 10/11 this writes the registry entries; user still selects via Settings.
// On macOS this may set it directly depending on OS version.
app.setAsDefaultProtocolClient('https');
app.setAsDefaultProtocolClient('http');
// Extract a navigable URL from a process argv array (set as default browser or open-with).
function getArgUrl(argv) {
for (const a of (argv || []).slice(1)) {
if (/^https?:\/\//i.test(a)) return a;
if (/^file:\/\//i.test(a)) return a;
// Windows: file path passed directly (e.g. double-click .html)
if (/\.(html?|xhtml|pdf)$/i.test(a)) {
try { if (fs.existsSync(a)) return pathToFileURL(a).href; } catch {}
}
}
return null;
}
// Single-instance lock: if RAW is already running and an external link is clicked,
// forward the URL to the existing window instead of opening a second instance.
const _gotSingleLock = app.requestSingleInstanceLock();
if (!_gotSingleLock) { app.quit(); }
app.on('second-instance', (_, argv) => {
if (!win) return;
if (win.isMinimized()) win.restore();
win.focus();
const url = getArgUrl(argv);
if (url) createTab(url, true);
});
// macOS: link clicked in another app while RAW is already running
let _pendingExtUrl = null;
app.on('open-url', (event, url) => {
event.preventDefault();
if (win) createTab(url, true);
else _pendingExtUrl = url;
});
const SPOOF_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
const SPOOF_UA_HINTS = '"Not_A Brand";v="8", "Chromium";v="131", "Google Chrome";v="131"';
// ── Global UA fallback ─────────────────────────────────────────────────────────
// The deepest possible override — covers every WebContents that has NOT had
// setUserAgent() called explicitly (service workers, pre-flight auth checks,
// non-partitioned popup windows, etc.). Must be set BEFORE app.whenReady().
app.userAgentFallback = SPOOF_UA;
// Set the UA at the Chromium process level — applies to every renderer, service
// worker, and sub-frame before any JS runs, overriding Electron's own binary string.
app.commandLine.appendSwitch('user-agent', SPOOF_UA);
// ── Enable features — ONE call; Chromium only honours the last value ──────────
// HardwareMediaKeyHandling + MediaSessionService: media keys & OS media HUD.
// PlatformEncryptedMediaFoundation (win32 only): DRM via Media Foundation.
//
// NOTE: StoragePartitioning and BlockThirdPartyCookies are intentionally NOT
// enabled here. In Chromium 120+ (Electron 36+) these features operate BELOW
// Electron's webRequest layer and block third-party cookies/storage for DRM
// license servers (e.g. spclient.wg.spotify.com) even when those domains are
// whitelisted in our request handlers. Removing them fixes Widevine/Spotify DRM.
// Cross-site isolation is still enforced by our webRequest interceptors.
if (process.platform === 'win32') {
app.commandLine.appendSwitch('enable-features',
'HardwareMediaKeyHandling,MediaSessionService,PlatformEncryptedMediaFoundation');
} else {
app.commandLine.appendSwitch('enable-features',
'HardwareMediaKeyHandling,MediaSessionService');
}
// ── Disable features — ONE call; Chromium only honours the last value ─────────
// NetworkPrediction: no speculative pre-connections leaking browsing intent.
// DnsOverHttps: disable Chromium's built-in DoH (use OS resolver).
// PrefetchPrivacyChanges: keep prefetch from pinging third-party hosts.
// WebRtcHideLocalIpsWithMdns: expose real IP (mDNS can interfere with WebRTC).
// WebAuthentication*: suppress Windows Hello / FIDO2 / passkey dialogs.
app.commandLine.appendSwitch('disable-features',
'NetworkPrediction,DnsOverHttps,PrefetchPrivacyChanges,' +
'WebRtcHideLocalIpsWithMdns,WebAuthentication,WebAuthenticationCableSecondFactor,' +
'WebAuthenticationPasskeysInBrowserWindow,WebAuthenticationRemoteDesktopSupport');
app.commandLine.appendSwitch('no-pings'); // suppress <a ping=> hyperlink auditing
// ── Anti-bot detection flags ─────────────────────────────────────────────────
// Remove Electron-specific infobars / first-run markers that differ from Chrome.
app.commandLine.appendSwitch('disable-infobars');
app.commandLine.appendSwitch('no-first-run');
app.commandLine.appendSwitch('no-default-browser-check');
// Disable component extensions (Chrome's built-in internal extensions like PDF
// viewer) — Electron loads different ones which can be detected via chrome.runtime.
app.commandLine.appendSwitch('disable-component-extensions-with-background-pages');
// Ensure the user-data-dir doesn't leak an Electron-specific path in error reports
app.commandLine.appendSwitch('disable-crash-reporter');
// ── YouTube stealth ad-skip content script ────────────────────────────────────
// This is used as an Add-On (ext key: 'yt-ad') — NOT injected automatically.
// Design:
// • Random variable key per-injection — can't be fingerprinted by name
// • MutationObserver reacts to player class changes and specific ad nodes only
// • Polling fallback every 600ms (lightweight, ad-in-progress only)
// • Saves/restores user mute, volume, playbackRate across each ad
// • Dismisses skip buttons, overlay ads, and bot-check dialogs
// • No canvas/pixel readback — avoids GPU stalls and fingerprinting risk
const YT_AD_SKIP = `(function(){
// YouTube Shorts — do NOT run ad-skip logic here.
// Shorts uses the same player infrastructure but seeking/speeding breaks playback.
if(window.location.pathname.indexOf('/shorts/')===0)return;
// Re-entrant guard with cleanup of prior instance
var _k='_rb'+Math.random().toString(36).slice(2,7);
if(window._rbYtAdKey){
try{window[window._rbYtAdKey].obs.disconnect();}catch(e){}
if(window[window._rbYtAdKey]&&window[window._rbYtAdKey].iv)
clearInterval(window[window._rbYtAdKey].iv);
// Clean up any pending wait-observer from a previous injection
if(window[window._rbYtAdKey]&&window[window._rbYtAdKey].wObs)
try{window[window._rbYtAdKey].wObs.disconnect();}catch(e){}
delete window[window._rbYtAdKey];
}
window._rbYtAdKey=_k;
// ── CSS: hide every known non-video ad surface ─────────────────────────────
if(!document.getElementById('_rb_ac')){
var _s=document.createElement('style');
_s.id='_rb_ac';
_s.textContent=
'ytd-promoted-sparkles-text-search-renderer,ytd-promoted-video-renderer,'+
'ytd-display-ad-renderer,ytd-banner-promo-renderer,#masthead-ad,'+
'ytd-ad-slot-renderer,ytd-in-feed-ad-layout-renderer,'+
'ytd-action-companion-ad-renderer,ytd-companion-slot-renderer,'+
'ytd-statement-banner-renderer,.ytd-merch-shelf-renderer,'+
'#player-ads>.ytd-watch-flexy,#frosted-glass-container,'+
'.ytp-ad-overlay-container,.ytp-ce-covering-ad,'+
'.ytp-ce-element,.ytp-ce-covering-overlay,'+
'.ytp-suggested-action,.ytp-ad-module,'+
'[id^="google_ads_iframe"],[id^="aswift_"],'+
'.ad-showing .ytp-pause-overlay,'+
'.ad-interrupting .ytp-pause-overlay,'+
'.ytp-ad-text,.ytp-ad-preview-container,.ytp-ad-badge-container,'+
'.ytp-ad-message-container,.ytp-ad-image-overlay,.ytp-ad-overlay-ad-info-button-container,'+
'ytd-player-legacy-desktop-watch-ads-renderer,'+
'.ytp-ad-persistent-progress-bar-container,'+
'.ytp-ad-progress-list,.ytp-ad-simple-ad-badge,'+
'ytd-display-ad-renderer[slot],ytd-action-companion-ad-renderer[slot],'+
'.ytd-video-masthead-ad-v3-renderer,#video-masthead-ad,'+
'ytd-companion-slot-renderer[slot],'+
'ytd-rich-item-renderer:has(.ytd-ad-slot-renderer),'+
'ytd-rich-section-renderer:has(ytd-statement-banner-renderer)'+
'{display:none!important}';
(document.head||document.documentElement).appendChild(_s);
}
var _wasInAd=false;
var _userMuted=false,_userRate=1,_userVolume=1;
var _restoreTimer=null;
function _inAd(player){
if(player&&(player.classList.contains('ad-showing')||
player.classList.contains('ad-interrupting')))return true;
if(document.querySelector('.ytp-ad-player-overlay-instream-info'))return true;
if(document.querySelector('.ytp-ad-persistent-progress-bar-container'))return true;
var adText=document.querySelector('.ytp-ad-text,.ytp-ad-simple-ad-badge');
if(adText&&adText.offsetParent!==null)return true;
var skipBtn=document.querySelector('.ytp-ad-skip-button,.ytp-ad-skip-button-modern,.ytp-skip-ad-button,.ytp-ad-skip-button-slot');
if(skipBtn&&skipBtn.offsetParent!==null)return true;
var progList=document.querySelector('.ytp-ad-progress-list');
if(progList&&progList.offsetParent!==null)return true;
return false;
}
function _getVideo(){
return document.querySelector('#movie_player video.html5-main-video')||
document.querySelector('#movie_player video')||
document.querySelector('video');
}
function _act(){
try{
// 1. Click any visible skip button — cleanest outcome
var skipBtns=document.querySelectorAll(
'.ytp-ad-skip-button-modern,.ytp-skip-ad-button,'+
'.ytp-ad-skip-button,.ytp-ad-skip-button-slot .ytp-button,'+
'button.ytp-ad-skip-button-modern,'+
'.ytp-ad-skip-button-container button'
);
for(var si=0;si<skipBtns.length;si++){
var skip=skipBtns[si];
if(skip&&skip.offsetParent!==null&&!skip.hidden&&skip.offsetWidth>0){
skip.click();
setTimeout(_act,350);
return;
}
}
var player=document.querySelector('#movie_player,.html5-video-player');
var video=_getVideo();
var inAd=_inAd(player);
if(inAd&&video&&video.readyState>0){
if(!_wasInAd){
// Save user state on first ad frame only; ignore if already at ad speed
_userMuted=video.muted;
_userRate=(video.playbackRate>2)?1:video.playbackRate;
_userVolume=video.volume;
}
_wasInAd=true;
if(!video.muted)video.muted=true;
if(video.playbackRate<8)try{video.playbackRate=16;}catch(e){}
if(video.duration&&isFinite(video.duration)&&video.duration>0.5){
try{video.currentTime=Math.max(0,video.duration-0.15);}catch(e){}
}
if(video.paused&&video.readyState>0)try{video.play();}catch(e){}
} else if(_wasInAd&&!inAd){
_wasInAd=false;
if(_restoreTimer)clearTimeout(_restoreTimer);
_restoreTimer=setTimeout(function(){
var v=_getVideo();
if(v){
try{v.playbackRate=_userRate||1;}catch(e){}
try{v.muted=_userMuted;}catch(e){}
try{v.volume=_userVolume;}catch(e){}
if(v.paused&&v.readyState>0)try{v.play();}catch(e){}
}
_restoreTimer=null;
},350);
}
// 2. Dismiss overlay close buttons
document.querySelectorAll(
'.ytp-ad-overlay-close-button,.ytp-ad-overlay-slot-close-button,'+
'.ytp-suggested-action-badge-expanded-close-button,'+
'.ytp-ad-overlay-close-container'
).forEach(function(el){try{el.click();}catch(e){}});
// 3. Dismiss bot-check / ad-block enforcement dialogs
var botDlg=document.querySelector(
'ytd-enforcement-message-view-model,'+
'tp-yt-paper-dialog[id*="confirm"],'+
'ytd-watch-modal tp-yt-paper-dialog,'+
'ytd-modal-with-title-and-button-renderer'
);
if(botDlg&&botDlg.offsetParent!==null){
var watchBtn=botDlg.querySelector(
'button[aria-label*="without" i],button[aria-label*="Continue" i],'+
'button[aria-label*="Watch" i],button[aria-label*="Dismiss" i],'+
'.yt-spec-button-shape-next--filled,.yt-spec-button-shape-next--tonal'
);
if(!watchBtn){
var btns=botDlg.querySelectorAll('button,.yt-spec-button-shape-next');
if(btns.length)watchBtn=btns[btns.length-1];
}
if(watchBtn){try{watchBtn.click();}catch(e){}}
}
}catch(e){}
}
// ── MutationObserver — only fires on ad-relevant class/node changes ─────────
// Observes player attribute changes + ad node additions only (no subtree sieve).
var _obs=new MutationObserver(function(muts){
var needAct=false;
for(var i=0;i<muts.length;i++){
var t=muts[i].target;
// Attribute change on player (ad-showing / ad-interrupting class)
if(muts[i].type==='attributes'&&t&&t.classList&&(
t.classList.contains('ad-showing')||
t.classList.contains('ad-interrupting')
)){needAct=true;break;}
// Node additions — only care if a known ad node was inserted
var added=muts[i].addedNodes;
for(var j=0;j<added.length;j++){
var n=added[j];
if(n.nodeType!==1)continue;
var c=n.className||'';
if(c.indexOf('ytp-ad')!==-1||c.indexOf('ad-showing')!==-1||c.indexOf('ad-interrupting')!==-1){
needAct=true;break;
}
}
if(needAct)break;
}
if(needAct)_act();
});
// ── Polling fallback — only active while an ad is in progress ──────────────
var _iv=setInterval(function(){
var p=document.querySelector('#movie_player,.html5-video-player');
if(_inAd(p)||_wasInAd)_act();
},600);
window[_k]={obs:_obs,iv:_iv};
function _attach(){
var p=document.querySelector('#movie_player,.html5-video-player,ytd-player');
if(p){
_obs.observe(p,{childList:true,subtree:true,attributes:true,attributeFilter:['class']});
} else {
// Player hasn't rendered yet — wait for it
var _w=new MutationObserver(function(){
var p2=document.querySelector('#movie_player,.html5-video-player,ytd-player');
if(p2){
_w.disconnect();
if(window[_k])window[_k].wObs=null;
_obs.observe(p2,{childList:true,subtree:true,attributes:true,attributeFilter:['class']});
}
});
_w.observe(document.body||document.documentElement,{childList:true,subtree:false});
// Save reference so re-entry cleanup can disconnect it if still pending
if(window[_k])window[_k].wObs=_w;
}
}
_attach();
_act();
// Catch late-loading player and in-roll ads on navigation
setTimeout(_act,400);
setTimeout(_act,1500);
setTimeout(_act,3500);
})();`;
// ── YouTube ad-tracking URLs to block at network level ────────────────────────
// Only ad analytics/impression/delivery endpoints — video content is never blocked.
const YT_AD_BLOCK_PATTERNS = [
/youtube\.com\/api\/stats\/ads/i,
/youtube\.com\/pagead\//i,
/youtube\.com\/ptracking/i,
/googlevideo\.com\/api\/stats\/ads/i,
/googleads\.g\.doubleclick\.net/i,
/pubads\.g\.doubleclick\.net/i, // publisher ad delivery
/securepubads\.g\.doubleclick\.net/i,
/static\.doubleclick\.net/i,
/ad\.doubleclick\.net/i,
/s0\.2mdn\.net/i,
// NOTE: imasdk.googleapis.com intentionally NOT blocked — blocking it causes
// YouTube's player to hang on a black screen because the ad framework can't
// initialize, which prevents content playback entirely.
/googleadservices\.com/i,
/googlesyndication\.com/i,
/youtube\.com\/pagead\/paralleladview/i,
/youtube\.com\/api\/stats\/qoe\?.*adformat/i, // QoE only when ad-related
// 2024/2025 ad logging and survey endpoints
/jnn-pa\.googleapis\.com\/v1:logAdEvent/i,
/youtube\.com\/api\/stats\/watchtime\?.*ad/i,
/youtube\.com\/pagead\/adview/i,
/youtube\.com\/pagead\/viewthroughconversion/i,
];
// ── Google / auth UA fix ────────────────────────────────────────────────────
// Injected via executeJavaScript (runs in the page's MAIN world, NOT preload
// isolated world, and ignores CSP entirely). This overrides navigator.userAgentData
// so Google's sign-in never sees the real "Electron" brand, which triggers the
// "This browser may not be secure" error at the password step.
// Must run on EVERY navigation to google.com / accounts.google.com etc.
//
// KEY ANTI-DETECTION: Google's scripts use Function.prototype.toString() and
// Object.getOwnPropertyDescriptor() to detect if properties have been overridden
// with custom getters. We wrap both so our overrides appear native.
const GOOGLE_UA_FIX = `(function(){
if(window._rbGoogleFix)return;
window._rbGoogleFix=true;
try{
/* ── Step 0: Function.prototype.toString stealth ────────────────────────
Google checks if getters are native by calling fn.toString() and looking
for "[native code]". We wrap toString so all our custom getters report
as native. This MUST happen before any _def calls. */
var _fakeNatives=new WeakSet();
var _origFnToStr=Function.prototype.toString;
var _toStrProxy=function toString(){
if(_fakeNatives.has(this))return'function '+((this.name||'')||'')+'() { [native code] }';
return _origFnToStr.call(this);
};
_fakeNatives.add(_toStrProxy);
Function.prototype.toString=_toStrProxy;
/* Also protect Function.prototype.call/apply/bind.toString from revealing overrides */
try{Object.defineProperty(Function.prototype,'toString',{writable:true,configurable:true});}catch(e){}
/* ── Step 0b: Object.getOwnPropertyDescriptor stealth ──────────────────
Google also uses Object.getOwnPropertyDescriptor(navigator, prop) to
inspect property descriptors and detect custom getters. We intercept
queries for key navigator properties and return native-looking descriptors. */
var _origGOPD=Object.getOwnPropertyDescriptor;
var _spoofedProps=new Map(); /* target -> Set of prop names */
Object.getOwnPropertyDescriptor=function(obj,prop){
var s=_spoofedProps.get(obj);
if(s&&s.has(prop)){
/* Return descriptor on Navigator.prototype instead — looks like the native one */
var d=_origGOPD.call(Object,Object.getPrototypeOf(obj)||obj,prop);
if(d)return d;
}
return _origGOPD.call(Object,obj,prop);
};
_fakeNatives.add(Object.getOwnPropertyDescriptor);
var _UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
var _br=[{brand:'Not_A Brand',version:'8'},{brand:'Chromium',version:'131'},{brand:'Google Chrome',version:'131'}];
var _fvl=[{brand:'Not_A Brand',version:'8.0.0.0'},{brand:'Chromium',version:'131.0.6778.205'},{brand:'Google Chrome',version:'131.0.6778.205'}];
var _aud={
brands:_br, mobile:false, platform:'Windows',
getHighEntropyValues:function getHighEntropyValues(hints){
return Promise.resolve({architecture:'x86',bitness:'64',brands:_br,
fullVersionList:_fvl,mobile:false,model:'',
platform:'Windows',platformVersion:'10.0.0',uaFullVersion:'131.0.6778.205',
wow64:false});
},
toJSON:function toJSON(){return {brands:_br,mobile:false,platform:'Windows'};}
};
_fakeNatives.add(_aud.getHighEntropyValues);
_fakeNatives.add(_aud.toJSON);
function _def(t,p,v){
try{
var g=function(){return v;};
_fakeNatives.add(g);
Object.defineProperty(t,p,{get:g,configurable:true});
/* Track overridden props so GOPD can spoof them */
if(!_spoofedProps.has(t))_spoofedProps.set(t,new Set());
_spoofedProps.get(t).add(p);
}catch(e){}
}
_def(navigator,'userAgentData',_aud);
_def(navigator,'webdriver',false);
_def(navigator,'userAgent',_UA);
_def(navigator,'appVersion','5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36');
_def(navigator,'vendor','Google Inc.');
_def(navigator,'platform','Win32');
_def(navigator,'language','en-US');
_def(navigator,'languages',Object.freeze(['en-US','en']));
_def(navigator,'hardwareConcurrency',8);
_def(navigator,'pdfViewerEnabled',true);
_def(navigator,'cookieEnabled',true);
_def(navigator,'onLine',true);
_def(navigator,'maxTouchPoints',0);
_def(navigator,'appCodeName','Mozilla');
_def(navigator,'appName','Netscape');
_def(navigator,'product','Gecko');
_def(navigator,'productSub','20030107');
/* Plugins — Chrome always has PDF viewers; empty plugins is a strong signal */
try{
var _fp={name:'PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fp2={name:'Chrome PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fp3={name:'Chromium PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fp4={name:'Microsoft Edge PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fp5={name:'WebKit built-in PDF',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fpl=Object.assign([_fp,_fp2,_fp3,_fp4,_fp5],{namedItem:function(n){return n.includes('PDF')?_fp:null;},item:function(i){return[_fp,_fp2,_fp3,_fp4,_fp5][i]||null;},refresh:function(){}});
_def(navigator,'plugins',_fpl);
var _mt=Object.assign([{type:'application/pdf',description:'PDF',enabledPlugin:_fp,suffixes:'pdf'}],{namedItem:function(t){return t==='application/pdf'?{}:null;},item:function(i){return i===0?{}:null;}});
_def(navigator,'mimeTypes',_mt);
}catch(e){}
/* ── window.chrome — delete entirely and rebuild from scratch ───────────
Electron sets its own chrome.runtime with Electron-specific properties
(e.g. chrome.runtime.id pointing to internal extension). Assigning over
it may silently fail if properties are non-configurable. Deleting the
entire object and recreating it guarantees a clean Chrome-matching shape. */
try{delete window.chrome;}catch(e){} try{window.chrome=undefined;}catch(e){}
window.chrome={};
window.chrome.app={isInstalled:false,InstallState:{DISABLED:'disabled',INSTALLED:'installed',NOT_INSTALLED:'not_installed'},RunningState:{CANNOT_RUN:'cannot_run',READY_TO_RUN:'ready_to_run',RUNNING:'running'},getDetails:function getDetails(){return null;},getIsInstalled:function getIsInstalled(){return false;},installState:function installState(cb){if(cb)cb('not_installed');},runningState:function runningState(){return'cannot_run';}};
window.chrome.runtime={id:undefined,connect:function connect(){return{postMessage:function(){},onMessage:{addListener:function(){}},disconnect:function(){}};},sendMessage:function sendMessage(){},onMessage:{addListener:function(){}},onConnect:{addListener:function(){}},getPlatformInfo:function getPlatformInfo(cb){if(cb)cb({os:'win',arch:'x86-64',nacl_arch:'x86-64'});return Promise.resolve({os:'win',arch:'x86-64',nacl_arch:'x86-64'});},getManifest:function getManifest(){return undefined;},getURL:function getURL(){return'';},reload:function reload(){},requestUpdateCheck:function requestUpdateCheck(cb){if(cb)cb('no_update',{});}};
window.chrome.csi=function csi(){return{startE:Date.now(),onloadT:Date.now(),pageT:1000,tran:15};};
window.chrome.loadTimes=function loadTimes(){return{requestTime:Date.now()/1000,startLoadTime:Date.now()/1000,commitLoadTime:Date.now()/1000,finishDocumentLoadTime:Date.now()/1000,finishLoadTime:Date.now()/1000,firstPaintTime:Date.now()/1000,firstPaintAfterLoadTime:0,navigationType:'Other',wasFetchedViaSpdy:true,wasNpnNegotiated:true,npnNegotiatedProtocol:'h2',wasAlternateProtocolAvailable:false,connectionInfo:'h2'};};
/* Mark chrome.app/runtime/csi/loadTimes as fake-native for toString checks */
_fakeNatives.add(window.chrome.app.getDetails);_fakeNatives.add(window.chrome.app.getIsInstalled);
_fakeNatives.add(window.chrome.app.installState);_fakeNatives.add(window.chrome.app.runningState);
_fakeNatives.add(window.chrome.runtime.connect);_fakeNatives.add(window.chrome.runtime.sendMessage);
_fakeNatives.add(window.chrome.runtime.getPlatformInfo);_fakeNatives.add(window.chrome.runtime.getManifest);
_fakeNatives.add(window.chrome.runtime.getURL);_fakeNatives.add(window.chrome.runtime.reload);
_fakeNatives.add(window.chrome.runtime.requestUpdateCheck);
_fakeNatives.add(window.chrome.csi);_fakeNatives.add(window.chrome.loadTimes);
/* Block WebAuthn/Passkeys — Google falls back to password entry.
Keep PublicKeyCredential as a constructor but report no platform authenticator
(setting to undefined is detectable since Chrome always has it). */
try{
var _oc=navigator.credentials;
var _cg=function get(o){if(o&&o.publicKey)return Promise.reject(new DOMException('Not allowed','NotAllowedError'));return _oc?_oc.get.call(_oc,o):Promise.reject(new DOMException('Not allowed','NotAllowedError'));};
var _cc=function create(o){if(o&&o.publicKey)return Promise.reject(new DOMException('Not allowed','NotAllowedError'));return _oc?_oc.create.call(_oc,o):Promise.reject(new DOMException('Not allowed','NotAllowedError'));};
_fakeNatives.add(_cg);_fakeNatives.add(_cc);
Object.defineProperty(navigator,'credentials',{get:function(){return{get:_cg,create:_cc,preventSilentAccess:function(){return Promise.resolve();},store:function(c){return _oc?_oc.store.call(_oc,c):Promise.resolve();}};},configurable:true});
}catch(e){}
try{
if(typeof PublicKeyCredential!=='undefined'){
var _pkc=function PublicKeyCredential(){throw new TypeError("Illegal constructor");};
_pkc.isUserVerifyingPlatformAuthenticatorAvailable=function(){return Promise.resolve(false);};
_pkc.isConditionalMediationAvailable=function(){return Promise.resolve(false);};
_fakeNatives.add(_pkc);_fakeNatives.add(_pkc.isUserVerifyingPlatformAuthenticatorAvailable);_fakeNatives.add(_pkc.isConditionalMediationAvailable);
Object.defineProperty(window,'PublicKeyCredential',{value:_pkc,configurable:true,writable:true});
}
}catch(e){}
/* Headless detection: outerWidth/outerHeight === 0 in headless mode */
try{
var _ow=window.outerWidth||window.innerWidth||1280;
var _oh=window.outerHeight||window.innerHeight||720;
_def(window,'outerWidth',_ow);
_def(window,'outerHeight',_oh);
}catch(e){}
try{
_def(screen,'availWidth',screen.width||1920);
_def(screen,'availHeight',screen.height||1080);
_def(screen,'availLeft',0);
_def(screen,'availTop',0);
}catch(e){}
/* Remove Electron-specific globals */
try{delete window.Electron;}catch(e){}
try{delete window.__electron;}catch(e){}
try{delete window.__electronBinding;}catch(e){}
try{if(window.process)delete window.process;}catch(e){}
try{if(window.require)delete window.require;}catch(e){}
try{if(window.module)delete window.module;}catch(e){}
try{delete window.Buffer;}catch(e){}
try{delete window.global;}catch(e){}
try{delete window.__dirname;}catch(e){}
try{delete window.__filename;}catch(e){}
/* Remove non-Chrome browser identity signals */
try{delete window.opr;}catch(e){}
try{delete window.opera;}catch(e){}
try{if(navigator.brave)_def(navigator,'brave',undefined);}catch(e){}
try{if('globalPrivacyControl' in navigator)_def(navigator,'globalPrivacyControl',false);}catch(e){}
/* Remove automation/testing globals */
try{delete window.__nightmare;}catch(e){}
try{delete window.callPhantom;}catch(e){}
try{delete window._phantom;}catch(e){}
try{delete window.domAutomation;}catch(e){}
try{delete window.domAutomationController;}catch(e){}
try{delete window.cdc_adoQpoasnfa76pfcZLmcfl_Array;}catch(e){}
try{delete window.cdc_adoQpoasnfa76pfcZLmcfl_Promise;}catch(e){}
try{delete window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol;}catch(e){}
/* Remove Firefox/legacy signals */
try{delete window.controllers;}catch(e){}
try{delete window.Components;}catch(e){}
try{delete window.mozInnerScreenX;}catch(e){}
/* clientInformation alias */
try{if(!window.clientInformation)_def(window,'clientInformation',navigator);}catch(e){}
/* document.hasFocus() */
try{var _hf=function hasFocus(){return true;};_fakeNatives.add(_hf);Object.defineProperty(document,'hasFocus',{value:_hf,configurable:true,writable:true});}catch(e){}
/* navigator.connection */
try{if(!navigator.connection)_def(navigator,'connection',{effectiveType:'4g',rtt:50,downlink:10,saveData:false,addEventListener:function(){},removeEventListener:function(){}});}catch(e){}
/* speechSynthesis voices */
try{if(window.speechSynthesis){var _origGV=window.speechSynthesis.getVoices.bind(window.speechSynthesis);var _fv=[{voiceURI:'Google US English',name:'Google US English',lang:'en-US',localService:true,default:true},{voiceURI:'Google UK English Female',name:'Google UK English Female',lang:'en-GB',localService:false,default:false}];var _gvFn=function getVoices(){var r=_origGV();return(r&&r.length)?r:_fv;};_fakeNatives.add(_gvFn);window.speechSynthesis.getVoices=_gvFn;}}catch(e){}
/* Notification.permission */
try{if(typeof Notification!=='undefined')Object.defineProperty(Notification,'permission',{get:function(){return'default';},configurable:true});}catch(e){}
/* Permission API — return 'prompt' for all permission queries (matches fresh Chrome install) */
try{if(navigator.permissions){var _origQ=navigator.permissions.query.bind(navigator.permissions);var _pqFn=function query(desc){if(desc&&(desc.name==='notifications'||desc.name==='push'))return Promise.resolve({state:'prompt',status:'prompt',onchange:null});return _origQ(desc);};_fakeNatives.add(_pqFn);navigator.permissions.query=_pqFn;}}catch(e){}
/* Block service worker registration — SW context doesn't get our overrides,
so Google's SW could report real Electron identity back to the server. */
try{if(navigator.serviceWorker){var _origReg=navigator.serviceWorker.register.bind(navigator.serviceWorker);var _srFn=function register(){return Promise.reject(new DOMException('Failed to register a ServiceWorker','SecurityError'));};_fakeNatives.add(_srFn);navigator.serviceWorker.register=_srFn;}}catch(e){}
}catch(e){}
})();
`;
const _GOOGLE_RE = /google\.com|googleapis\.com|gstatic\.com|gmail\.com|youtube\.com/i;
function _injectGoogleUAFix(wc) {
if (!wc || wc.isDestroyed()) return;
try {
const url = wc.getURL();
if (url && _GOOGLE_RE.test(url)) {
wc.executeJavaScript(GOOGLE_UA_FIX).catch(() => {});
}
} catch {}
}
// ── Video PiP — injected into every BV page ──────────────────────────────────
// Button appears at the TOP-RIGHT corner of the video element itself.
// Shows on hover (YouTube / any site) and on autoplay without hover (TikTok).
// Real in-page click → requestPictureInPicture works everywhere.
const VIDEO_PIP_INJECT = `(function(){
// Cleanup any prior instance — disconnects observers and clears intervals
// to prevent accumulation on SPA navigations (especially YouTube Shorts).
if(window._rawPipCleanup){try{window._rawPipCleanup();}catch(e){}}
if(window._rawPipV3)return;
window._rawPipV3=true;
/* ── Floating PiP button — positioned over video top-right ── */
var btn=document.createElement('button');
btn.id='_rawPipBtn';
btn.style.cssText=
'position:fixed;z-index:2147483647;top:12px;right:12px;'+
'background:rgba(0,0,0,.72);color:#fff;'+
'border:none;border-radius:7px;'+
'padding:6px 12px 6px 9px;font:600 11px/1.2 -apple-system,sans-serif;'+
'cursor:pointer;display:flex;align-items:center;gap:5px;'+
'backdrop-filter:blur(10px);white-space:nowrap;'+
'box-shadow:0 2px 12px rgba(0,0,0,.65);'+
'opacity:0;pointer-events:none;'+
'transition:opacity .16s;';
btn.innerHTML=
'<svg width="12" height="12" viewBox="0 0 14 14" fill="none" style="flex-shrink:0">'+
'<rect x="1" y="2" width="12" height="9" rx="1.5" stroke="currentColor" stroke-width="1.3"/>'+
'<rect x="6.5" y="6" width="5.5" height="4" rx="1" fill="currentColor" opacity=".75"/>'+
'</svg><span id="_rawPipLbl">Pop Out</span>';
document.documentElement.appendChild(btn);
var _pip=false, _activeV=null, _hideTimer=null, _ro=null;
/* ── Position button at top-right of a video element ── */
function _pos(v){
if(!v)return;
var r=v.getBoundingClientRect();
var bw=btn.offsetWidth||90;
btn.style.top=Math.max(8,r.top+8)+'px';
btn.style.left=Math.max(0,r.right-bw-8)+'px';
btn.style.right='auto';
btn.style.bottom='auto';
}
function _show(v){
clearTimeout(_hideTimer);
if(v)_activeV=v;
if(_activeV)_pos(_activeV);
btn.style.opacity='1';
btn.style.pointerEvents='all';
}
function _hide(delay){
clearTimeout(_hideTimer);
_hideTimer=setTimeout(function(){
btn.style.opacity='0';
btn.style.pointerEvents='none';
},delay||0);
}
/* Reposition when user scrolls/resizes (keeps button glued to video) */
function _repos(){
if(btn.style.opacity==='1'&&_activeV){ _pos(_activeV); }
}
window.addEventListener('scroll',_repos,{passive:true,capture:true});
window.addEventListener('resize',_repos,{passive:true});
/* ── Bind hover events directly to a video element ── */
function _bindVideo(v){
if(v._rawPipBound)return;
v._rawPipBound=true;
v.addEventListener('mouseenter',function(){_show(v);},true);
v.addEventListener('mouseleave',function(e){
/* Don't hide if mouse moved onto the button */
if(!_pip&&e.relatedTarget!==btn)_hide(550);
},true);
/* Track video resize/position changes so button stays glued to the video */
if(typeof ResizeObserver!=='undefined'){
if(_ro)_ro.disconnect();
_ro=new ResizeObserver(function(){ if(btn.style.opacity==='1'&&_activeV)_pos(_activeV); });
_ro.observe(v);
}
}
function _bindAll(){
document.querySelectorAll('video').forEach(_bindVideo);
}
_bindAll();
/* Watch for videos added dynamically (TikTok / YouTube SPA) */
var _mo=new MutationObserver(function(muts){
for(var i=0;i<muts.length;i++){
if(muts[i].addedNodes&&muts[i].addedNodes.length){ _bindAll(); break; }
}
});
_mo.observe(document.body||document.documentElement,{childList:true,subtree:true});
/* ── Also poll for autoplay videos the hover approach can't catch ── */
/* (TikTok: video plays full-screen without the user hovering) */
function _bestPlaying(){
var vw=window.innerWidth,vh=window.innerHeight,best=null,score=-1;
document.querySelectorAll('video').forEach(function(v){
if(v.paused||v.ended)return;
if(v.readyState<2&&v.videoWidth<1)return;
var r=v.getBoundingClientRect();
if(r.width<60||r.height<40)return;
if(r.right<=0||r.bottom<=0||r.left>=vw||r.top>=vh)return;
var s=(v.duration||0)*6+(r.width*r.height/6000);
if(s>score){score=s;best=v;}
});
return best;
}
function _poll(){
if(_pip){_show();return;}
var v=_bestPlaying();
if(v){ _bindVideo(v); _show(v); }
/* Don't auto-hide — let mouseleave / _hide handle it */
}
/* ── Video play/pause events ── */
document.addEventListener('play',function(e){
if(e.target&&e.target.tagName==='VIDEO'){ _bindVideo(e.target); _poll(); }
},true);
document.addEventListener('pause',function(e){
if(e.target&&e.target.tagName==='VIDEO'&&e.target===_activeV){
if(!_pip) _hide(800);
}
},true);
/* ── PiP state tracking ── */
document.addEventListener('enterpictureinpicture',function(){
_pip=true;
var lbl=document.getElementById('_rawPipLbl');
if(lbl)lbl.textContent='Exit PiP';
_show();
});
document.addEventListener('leavepictureinpicture',function(){
_pip=false;
var lbl=document.getElementById('_rawPipLbl');
if(lbl)lbl.textContent='Pop Out';
_hide(700);
});
/* Keep button visible when mouse is on it */
btn.addEventListener('mouseenter',function(){ clearTimeout(_hideTimer); });
btn.addEventListener('mouseleave',function(e){
if(!_pip&&e.relatedTarget!==_activeV) _hide(300);
});
/* ── Click: enter or exit PiP ── */
btn.addEventListener('click',function(e){
e.stopPropagation(); e.preventDefault();
if(document.pictureInPictureElement){
document.exitPictureInPicture().catch(function(){});
}else{
var v=_activeV||_bestPlaying()||
document.querySelector('#movie_player video')||
document.querySelector('.html5-video-player video')||
document.querySelector('video');
if(!v)return;
try{v.disablePictureInPicture=false;}catch(x){}
v.requestPictureInPicture().catch(function(err){
console.warn('[RAW PiP]',err.message);
});
}
});
/* ── Initial poll + recurring poll for autoplay sites ── */
var _polled=0, _slowIv=null;
var _fastIv=setInterval(function(){
_poll(); _polled++;
if(_polled>=60){ clearInterval(_fastIv); _slowIv=setInterval(_poll,4000); }
},1000);
_poll();
/* ── Cleanup function — called on re-injection to prevent observer/interval accumulation ── */
window._rawPipCleanup=function(){
try{_mo.disconnect();}catch(e){}
try{clearInterval(_fastIv);}catch(e){}
if(_slowIv)try{clearInterval(_slowIv);}catch(e){}
if(_ro)try{_ro.disconnect();}catch(e){}
window.removeEventListener('scroll',_repos,{capture:true});
window.removeEventListener('resize',_repos);
window._rawPipV3=false;
window._rawPipCleanup=null;
};
})();`;
// ── Extension content scripts (injected into BrowserView via executeJavaScript) ─
const EXT_SCRIPTS = {
'dark-mode':
`(function(){
if(document.getElementById('_rawDark'))return;
/* Step 1: Set color-scheme so native inputs render dark */
var s=document.createElement('style');s.id='_rawDark';
s.textContent=':root{color-scheme:dark!important;}'+
'::selection{background:rgba(0,180,160,.5)!important;}';
document.head.appendChild(s);
/* Step 2: Smart invert — only on light pages.
Checks actual computed background of html/body (falls back through
transparency chain), respects declared color-scheme:dark, and
skips sites that already have a dark-mode class on <html>/<body>.
SVG inline elements are re-inverted so icons stay natural. */
function _applyInvert(){
if(document.getElementById('_rawDarkInv'))return;
/* Check if site natively declared dark color-scheme */
try {
var cs = getComputedStyle(document.documentElement).colorScheme || '';
if(cs.includes('dark')) return;
} catch(e){}
/* Check for common dark-mode class names on root/body */
var rootCls = (document.documentElement.className||'')+' '+((document.body||{}).className||'');
if(/\b(dark|dark-mode|dark-theme|dark-layout|night|black-theme)\b/i.test(rootCls)) return;
/* Find real background — walk up from body through transparent layers */
var el=document.body||document.documentElement;
var bg=getComputedStyle(el).backgroundColor;
if(bg==='rgba(0, 0, 0, 0)'||bg==='transparent'){
bg=getComputedStyle(document.documentElement).backgroundColor;
}
var m=bg.match(/\\d+/g);
/* If still transparent or unreadable, assume light (invert) */
var lum=m&&m.length>=3?(+m[0]*299+(+m[1])*587+(+m[2])*114)/1000:210;
if(lum<90) return; /* page is already dark — skip */
var si=document.createElement('style');si.id='_rawDarkInv';
/* Apply filter to body. SVG added to re-invert list so inline icons
stay natural. iframe excluded — compositor layer conflict in Electron. */