-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPinterestPowerMenu.user.js
More file actions
2874 lines (2596 loc) · 121 KB
/
PinterestPowerMenu.user.js
File metadata and controls
2874 lines (2596 loc) · 121 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
// ==UserScript==
// @name Pinterest Power Menu
// @namespace https://github.com/Angel2mp3
// @version 1.3.3
// @description All-in-one Pinterest power tool: original quality, download fixer, video downloader, board folder downloader, GIF hover/auto-play, remove videos, hide Visit Site, declutter, hide UI elements, hide shop posts, hide comments, scroll preservation
// @author Angel2mp3
// @icon https://www.pinterest.com/favicon.ico
// @match https://www.pinterest.com/*
// @match https://pinterest.com/*
// @match https://*.pinterest.com/*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_setClipboard
// @connect *
// @run-at document-start
// @updateURL https://raw.githubusercontent.com/Angel2mp3/Pinterest-Power-Menu/main/PinterestPowerMenu.user.js
// @downloadURL https://raw.githubusercontent.com/Angel2mp3/Pinterest-Power-Menu/main/PinterestPowerMenu.user.js
// ==/UserScript==
(function () {
'use strict';
// ═══════════════════════════════════════════════════════════════════
// SETTINGS
// ═══════════════════════════════════════════════════════════════════
const SETTINGS_KEY = 'pe_settings_v1';
// ── Mobile / touch detection ─────────────────────────────────────────
// Declared early so DEFAULTS can reference it (contextMenu off on mobile).
// Gates features that are mouse-only or cause jank on touch devices.
const IS_MOBILE = /android|iphone|ipad|ipod|mobile/i.test(navigator.userAgent)
|| (navigator.maxTouchPoints > 1 && /macintel/i.test(navigator.platform));
const DEFAULTS = {
originalQuality: true,
downloadFixer: true,
gifHover: true,
hideVisitSite: true,
boardDownloader: true,
declutter: true,
contextMenu: !IS_MOBILE, // mouse-only feature; off by default on mobile
hideUpdates: false,
hideMessages: false,
hideShare: false,
gifAutoPlay: false,
removeVideos: false,
hideShopPosts: false,
hideComments: false,
videoDownloader: true,
};
let _cfg = null;
function loadCfg() {
try {
const raw = GM_getValue(SETTINGS_KEY, null);
_cfg = raw ? { ...DEFAULTS, ...JSON.parse(raw) } : { ...DEFAULTS };
} catch (_) {
_cfg = { ...DEFAULTS };
}
}
function saveCfg() {
GM_setValue(SETTINGS_KEY, JSON.stringify(_cfg));
}
function get(key) {
if (!_cfg) loadCfg();
return key in _cfg ? _cfg[key] : DEFAULTS[key];
}
function set(key, val) {
if (!_cfg) loadCfg();
_cfg[key] = val;
saveCfg();
}
loadCfg();
// ─── Video URL interceptor ──────────────────────────────────────────────
// On desktop, Pinterest uses HLS.js which sets video.src to a blob:
// MediaSource URL — findPinterestVideoSrc() cannot read the actual CDN URL
// from the DOM. Intercept XHR/fetch at document-start to capture
// v1.pinimg.com video URLs as they are requested by HLS.js, then use them
// as a fallback in createVideoDlFab().
const _interceptedVideoUrls = []; // most-recently-seen first
let _onVideoUrlCapture = null; // set after createVideoDlFab is defined
(function () {
function captureVideoUrl(url) {
if (typeof url !== 'string') return;
if (!/v1\.pinimg\.com\/videos/i.test(url)) return;
const idx = _interceptedVideoUrls.indexOf(url);
if (idx !== -1) _interceptedVideoUrls.splice(idx, 1);
_interceptedVideoUrls.unshift(url); // newest first
if (_interceptedVideoUrls.length > 20) _interceptedVideoUrls.pop();
if (typeof _onVideoUrlCapture === 'function') _onVideoUrlCapture();
}
const _xOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (m, url, ...a) {
captureVideoUrl(String(url));
return _xOpen.call(this, m, url, ...a);
};
const _oFetch = window.fetch;
if (typeof _oFetch === 'function') {
window.fetch = function (input) {
captureVideoUrl(typeof input === 'string' ? input : (input && input.url) || '');
return _oFetch.apply(this, arguments);
};
}
})();
// Utility: returns a debounced version of fn (resets timer on every call).
function debounce(fn, ms) {
let t;
return function () { clearTimeout(t); t = setTimeout(fn, ms); };
}
// ═══════════════════════════════════════════════════════════════════
// MODULE: ORIGINAL QUALITY (fast – no probe, no popup)
// ═══════════════════════════════════════════════════════════════════
// Directly rewrite pinimg.com thumbnail URLs → /originals/ with
// an inline onerror fallback to /736x/ so zero extra requests are
// made upfront and the "Optimizing…" overlay is never shown.
const OQ_RE = /^(https?:\/\/i\.pinimg\.com)\/\d+x(\/[0-9a-f]{2}\/[0-9a-f]{2}\/[0-9a-f]{2}\/[0-9a-f]{32}\.(?:jpg|jpeg|png|gif|webp))$/i;
function upgradeImg(img) {
if (!get('originalQuality')) return;
if (img.__peOQ || img.tagName !== 'IMG' || !img.src) return;
const m = img.src.match(OQ_RE);
if (!m) return;
img.__peOQ = true;
const origSrc = m[1] + '/originals' + m[2];
const fallSrc = m[1] + '/736x' + m[2];
img.onerror = function () {
if (img.src === origSrc) { img.onerror = null; img.src = fallSrc; }
};
if (img.getAttribute('data-src') === img.src) img.setAttribute('data-src', origSrc);
img.src = origSrc;
}
function scanOQ(node) {
if (!node || node.nodeType !== 1) return;
if (node.tagName === 'IMG') upgradeImg(node);
else node.querySelectorAll('img[src*="pinimg.com"]').forEach(upgradeImg);
}
// Start MutationObserver immediately (document-start) so we catch
// images before they fire their first load event.
const oqObs = new MutationObserver(records => {
if (!get('originalQuality')) return;
const process = () => records.forEach(r => {
if (r.attributeName === 'src') upgradeImg(r.target);
else r.addedNodes.forEach(scanOQ);
});
// On mobile, yield to the browser's render pipeline so scroll stays smooth
if (IS_MOBILE && typeof requestIdleCallback === 'function') {
requestIdleCallback(process, { timeout: 300 });
} else {
process();
}
});
oqObs.observe(document.documentElement, {
childList: true, subtree: true,
attributes: true, attributeFilter: ['src'],
});
// ═══════════════════════════════════════════════════════════════════
// MODULE: HIDE VISIT SITE
// ═══════════════════════════════════════════════════════════════════
// Uses CSS classes on <body> so toggles are instant and zero-cost.
function applyVisitSiteToggle() {
if (!document.body) return;
document.body.classList.toggle('pe-hide-visit', get('hideVisitSite'));
}
function applyNavToggles() {
if (!document.body) return;
document.body.classList.toggle('pe-hide-updates', get('hideUpdates'));
document.body.classList.toggle('pe-hide-messages', get('hideMessages'));
document.body.classList.toggle('pe-hide-share', get('hideShare'));
document.body.classList.toggle('pe-hide-comments', get('hideComments'));
}
// Physically removes the Messages nav button from the DOM (not just hidden with CSS).
// A MutationObserver re-removes it whenever Pinterest re-renders the nav (SPA navigation).
let _messagesRemoverObs = null;
function initMessagesRemover() {
if (!get('hideMessages')) return;
if (_messagesRemoverObs) return; // already running
const SELS = [
'div[aria-label="Messages"]',
'[data-test-id="nav-bar-speech-ellipsis"]',
];
function removeNow(root) {
SELS.forEach(sel => {
(root.querySelectorAll ? root.querySelectorAll(sel) : []).forEach(el => el.remove());
});
}
removeNow(document);
_messagesRemoverObs = new MutationObserver(recs => {
if (!get('hideMessages')) { _messagesRemoverObs.disconnect(); _messagesRemoverObs = null; return; }
recs.forEach(r => r.addedNodes.forEach(n => { if (n.nodeType === 1) removeNow(n); }));
});
_messagesRemoverObs.observe(document.documentElement, { childList: true, subtree: true });
}
// JS-based "Visit site" link removal – catches links that CSS alone misses
// (e.g. <a rel="nofollow"><div>Visit site</div></a>)
function initVisitSiteHider() {
function hideInTree(root) {
if (!get('hideVisitSite') || !root) return;
const links = root.querySelectorAll ? root.querySelectorAll('a') : [];
links.forEach(a => {
if (a.__peVisitHidden) return;
const text = a.textContent.trim();
if (/^visit\s*site$/i.test(text)) {
a.__peVisitHidden = true;
a.style.setProperty('display', 'none', 'important');
}
});
}
hideInTree(document);
new MutationObserver(recs => {
if (!get('hideVisitSite')) return;
recs.forEach(r => r.addedNodes.forEach(n => {
if (n.nodeType === 1) hideInTree(n);
}));
}).observe(document.documentElement, { childList: true, subtree: true });
}
// ═══════════════════════════════════════════════════════════════════
// MODULE: SHARE URL OVERRIDE
// ═══════════════════════════════════════════════════════════════════
// Replaces Pinterest's shortened pin.it URLs in the share dialog
// with the actual pin URL. On closeup pages that's location.href;
// on the grid we walk up from the share button to find the pin link.
// Also intercepts "Copy link" and clicks on the URL input box.
function initShareOverride() {
const nativeSetter = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value'
).set;
let _sharePinUrl = null;
// 1) Track share/send button clicks to capture the pin's real URL
document.addEventListener('click', e => {
const shareBtn = e.target.closest(
'[data-test-id="sendPinButton"], button[aria-label="Send"], ' +
'[data-test-id="closeup-share-button"], div[aria-label="Share"], ' +
'button[aria-label="Share"]'
);
if (!shareBtn) return;
// On a pin closeup page, location.href IS the pin URL
if (/\/pin\/\d+/.test(location.pathname)) {
_sharePinUrl = location.href;
return;
}
// On grid: walk up from the share button to find the pin card link
_sharePinUrl = null;
let el = shareBtn;
for (let i = 0; i < 30 && el; i++) {
if (el.querySelector) {
const link = el.querySelector('a[href*="/pin/"]');
if (link) {
_sharePinUrl = new URL(link.href, location.origin).href;
break;
}
}
el = el.parentElement;
}
if (!_sharePinUrl) _sharePinUrl = location.href;
}, true);
// 2) Watch for the share-popup URL input and override its value
function fixShareInputs() {
const realUrl = _sharePinUrl || location.href;
document.querySelectorAll(
'input#url-text, ' +
'[data-test-id="copy-link-share-icon-auth"] input[type="text"], ' +
'input[readonly][value*="pin.it"], ' +
'input[readonly][value*="pinterest.com/pin/"]'
).forEach(input => {
// Always re-fix if value doesn't match
if (input.value !== realUrl) {
nativeSetter.call(input, realUrl);
input.dispatchEvent(new Event('input', { bubbles: true }));
}
if (!input.__peShareClick) {
input.__peShareClick = true;
// Intercept clicks on the input box itself
input.addEventListener('click', ev => {
ev.stopPropagation();
const url = _sharePinUrl || location.href;
navigator.clipboard.writeText(url).catch(() => {
const ta = document.createElement('textarea');
ta.value = url;
ta.style.cssText = 'position:fixed;left:-9999px';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
});
}, true);
// Re-fix if React re-renders the value
new MutationObserver(() => {
const url = _sharePinUrl || location.href;
if (input.value !== url) {
nativeSetter.call(input, url);
input.dispatchEvent(new Event('input', { bubbles: true }));
}
}).observe(input, { attributes: true, attributeFilter: ['value'] });
}
});
}
new MutationObserver(fixShareInputs)
.observe(document.documentElement, { childList: true, subtree: true });
// 3) Intercept "Copy link" button clicks
document.addEventListener('click', e => {
const copyBtn = e.target.closest(
'button[aria-label="Copy link"], ' +
'[data-test-id="copy-link-share-icon-auth"] button'
);
if (!copyBtn) return;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
const realUrl = _sharePinUrl || location.href;
navigator.clipboard.writeText(realUrl).then(() => {
const txt = copyBtn.querySelector('div');
if (txt) {
const orig = txt.textContent;
txt.textContent = 'Copied!';
setTimeout(() => { txt.textContent = orig; }, 1500);
}
}).catch(() => {
const ta = document.createElement('textarea');
ta.value = realUrl;
ta.style.cssText = 'position:fixed;left:-9999px';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
});
}, true);
}
// ═══════════════════════════════════════════════════════════════════
// MODULE: GIF / VIDEO HOVER PLAY
// ═══════════════════════════════════════════════════════════════════
// In the pin grid, Pinterest renders GIFs as static <img> elements
// (showing a .jpg thumbnail) with the real .gif URL hidden in
// srcset at "4x". There is no <video> in the grid.
//
// Strategy:
// • On mouseover – walk up to [data-test-id="pinWrapper"], find
// img[srcset*=".gif"], extract the .gif URL, swap img.src to it.
// • On mouseout – restore the original .jpg src.
// • Only ONE gif plays at a time (previous is restored before new starts).
// • <video> elements (pin closeup / detail page) are still kept paused
// via the MutationObserver so they don't auto-play in the background.
// Selector matching any img that carries a GIF URL in srcset, live src, or lazy data-src.
// Used by both hover-play and auto-play modules.
const GIF_IMG_SEL = 'img[srcset*=".gif"], img[src*=".gif"], img[data-src*=".gif"]';
const GIF_PIN_CONTAINER_SEL = [
'[data-test-id="pinWrapper"]',
'[data-grid-item="true"]',
'[data-test-id="pin"]',
'div[role="listitem"]',
'[data-test-id="pin-closeup-image"]',
].join(', ');
let _gifActiveImg = null; // <img> currently showing a .gif
let _gifOrigSrc = null; // original src to restore on leave
let _gifOrigSrcset = null; // original srcset to restore on leave
let _gifActiveCont = null; // pinWrapper of the active gif
let _gifActiveVid = null; // <video> currently playing a GIF (mobile hover/tap)
// Pinterest uses different card wrappers across home/search/closeup pages,
// especially on mobile. Resolve the nearest usable pin container defensively.
function findGifContainer(node) {
if (!node || node.nodeType !== 1) return null;
return node.closest(GIF_PIN_CONTAINER_SEL);
}
// Resolve a video source even when Pinterest lazy-loads into data-* attrs.
function getVideoSrc(video) {
if (!video) return '';
const source = video.querySelector && video.querySelector('source');
return video.src
|| video.getAttribute('src')
|| video.getAttribute('data-src')
|| (source && (source.src || source.getAttribute('src') || source.getAttribute('data-src')))
|| '';
}
// Ensure lazy mobile GIF videos have a concrete src before play() attempts.
function hydrateVideoSource(video) {
if (!video) return;
if (!video.getAttribute('src')) {
const ds = video.getAttribute('data-src');
if (ds) video.setAttribute('src', ds);
}
const source = video.querySelector && video.querySelector('source');
if (source && !source.getAttribute('src')) {
const ds = source.getAttribute('data-src');
if (ds) source.setAttribute('src', ds);
}
}
// Classify whether a <video> is a GIF-like pin media.
// Some mobile layouts use i.pinimg.com sources, others expose only
// a PinTypeIdentifier badge with text "GIF".
function isGifVideo(video, container) {
if (!video) return false;
const src = getVideoSrc(video);
if (/i\.pinimg\.com/i.test(src)) return true;
const wrap = container || findGifContainer(video);
const badge = wrap && wrap.querySelector('[data-test-id="PinTypeIdentifier"]');
if (!badge) return false;
const t = (badge.textContent || '').trim().toLowerCase();
if (t === 'gif' || t.includes('animated')) return true;
if (t === 'video' || t.includes('watch')) return false;
return false;
}
// Detect the mobile/touch layout GIF pin — Pinterest renders these with
// JPEG-only srcset; the GIF container data-test-ids identify them reliably.
function isMobileGifPin(container) {
if (!container) return false;
if (container.querySelector('[data-test-id="inp-perf-pinType-gif"]')) return true;
if (container.querySelector('[data-test-id="pincard-gif-without-link"]')) return true;
const badge = container.querySelector('[data-test-id="PinTypeIdentifier"]');
if (badge) {
const t = (badge.textContent || '').trim().toLowerCase();
if (t === 'gif' || t.includes('animated')) return true;
}
return false;
}
// Convert a pinimg.com JPEG/WebP thumbnail URL to the /originals/ GIF URL.
// e.g. …/236x/ab/cd/ef/hash.jpg → …/originals/ab/cd/ef/hash.gif
function deriveGifUrl(jpegUrl) {
if (!jpegUrl) return null;
const m = jpegUrl.match(/^(https?:\/\/i\.pinimg\.com)\/[^/]+(\/.+?)(?:\.jpe?g|\.webp)(\?.*)?$/i);
if (!m) return null;
return m[1] + '/originals' + m[2] + '.gif';
}
// Extract the .gif URL from an img element, checking srcset, live src, and data-src.
// On mobile Pinterest uses JPEG-only srcset for GIF pins; derive the .gif URL when needed.
function getGifSrcFromImg(img) {
if (!img) return null;
// Prefer srcset (Pinterest hides the GIF at "4x"; also stored in __peAutoOrigSrcset)
const srcset = img.getAttribute('srcset') || img.__peAutoOrigSrcset || '';
for (const part of srcset.split(',')) {
const url = part.trim().split(/\s+/)[0];
if (url && /\.gif(\?|$)/i.test(url)) return url;
}
// GIF already in src (srcset was cleared and .gif URL was applied)
if (/\.gif(\?|$)/i.test(img.src)) return img.src;
// Lazy-loaded src attribute
const ds = img.getAttribute('data-src') || '';
if (/\.gif(\?|$)/i.test(ds)) return ds;
// Mobile layout: GIF pins have JPEG-only srcset but carry inp-perf-pinType-gif /
// pincard-gif-without-link in their container. Derive the originals .gif URL.
const wrap = img.closest('[data-test-id="pinWrapper"], [data-grid-item="true"], [data-test-id="pin"]');
if (isMobileGifPin(wrap)) {
const jpegSrc = img.getAttribute('src') || img.src || '';
if (jpegSrc) {
const d = deriveGifUrl(jpegSrc);
if (d) return d;
}
// Fallback: try highest-res srcset entry
const parts = srcset.split(',').map(p => p.trim().split(/\s+/)[0]).filter(Boolean);
for (let i = parts.length - 1; i >= 0; i--) {
const d = deriveGifUrl(parts[i]);
if (d) return d;
}
}
return null;
}
function pauseActiveGif() {
if (_gifActiveImg) {
// Restore srcset FIRST so the browser doesn't re-pick from it
// before we restore src
if (_gifOrigSrcset !== null) _gifActiveImg.setAttribute('srcset', _gifOrigSrcset);
if (_gifOrigSrc !== null) _gifActiveImg.src = _gifOrigSrc;
}
if (_gifActiveVid) {
try { _gifActiveVid.pause(); } catch (_) {}
_gifActiveVid = null;
}
const prevCont = _gifActiveCont;
_gifActiveImg = null;
_gifOrigSrc = null;
_gifOrigSrcset = null;
_gifActiveCont = null;
// If GIF auto-play is active, let it take over this wrapper
if (prevCont && get('gifAutoPlay') && _gifAutoIO) {
setTimeout(() => {
const r = prevCont.getBoundingClientRect();
if (r.top < window.innerHeight && r.bottom > 0) startGifInView(prevCont);
}, 50);
}
}
// Keep any <video> elements (pin detail/closeup page) paused so they
// don't auto-play in the background.
function pauseVidOnAdd(v) {
if (v.__pePaused || v.__peGifVid) return;
// GIFs rendered as <video src="i.pinimg.com/…"> on mobile must NOT be paused here —
// the GIF hover / auto-play modules manage those independently.
const getSrc = () => getVideoSrc(v);
const src = getSrc();
const initialWrap = findGifContainer(v);
if (isGifVideo(v, initialWrap)) {
v.__peGifVid = true;
return;
}
// src not yet assigned (lazy-load): observe for when it is set before deciding to pause.
// Without this, Pinterest's async src assignment races with auto-play on mobile —
// the deferred kill() calls would pause the video after auto-play had already started it.
if (!src) {
if (v.__peVidSrcObs) return; // observer already attached
v.__peVidSrcObs = true;
const obs = new MutationObserver(() => {
const s = getSrc();
if (!s) return; // still not set – keep waiting
obs.disconnect();
v.__peVidSrcObs = false;
const wrap = findGifContainer(v);
if (isGifVideo(v, wrap)) {
// It's a mobile GIF video – let hover / auto-play manage it; never pause it
v.__peGifVid = true;
const pw = wrap;
if (pw && _gifAutoIO) { pw.__peAutoObs = false; observeGifPins(); }
} else {
pauseVidOnAdd(v); // real video – go ahead and pause it
}
});
obs.observe(v, { attributes: true, attributeFilter: ['src'], childList: true });
return;
}
v.__pePaused = true;
v.muted = true;
const kill = () => { try { v.pause(); } catch (_) {} };
kill(); setTimeout(kill, 60); setTimeout(kill, 250);
}
new MutationObserver(records => {
records.forEach(r => r.addedNodes.forEach(function scan(n) {
if (!n || n.nodeType !== 1) return;
if (n.tagName === 'VIDEO') pauseVidOnAdd(n);
n.querySelectorAll && n.querySelectorAll('video').forEach(pauseVidOnAdd);
}));
}).observe(document.documentElement, { childList: true, subtree: true });
function initGifHover() {
document.addEventListener('mouseover', e => {
if (!get('gifHover')) return;
const pinWrapper = findGifContainer(e.target);
if (!pinWrapper || pinWrapper === _gifActiveCont) return;
// Look for a GIF image inside this pin card (incl. mobile JPEG-srcset GIF pins)
const img = pinWrapper.querySelector(GIF_IMG_SEL)
|| (isMobileGifPin(pinWrapper) ? pinWrapper.querySelector('img') : null);
if (!img) return;
const gifUrl = getGifSrcFromImg(img);
if (!gifUrl) return;
// Stop the previous gif first
pauseActiveGif();
// Start the new one.
// IMPORTANT: browsers use srcset over src, so we must clear srcset
// before setting src to the gif URL, otherwise src change is ignored.
_gifActiveImg = img;
_gifOrigSrc = img.src;
_gifOrigSrcset = img.getAttribute('srcset');
_gifActiveCont = pinWrapper;
img.removeAttribute('srcset'); // prevent srcset overriding our src
img.src = gifUrl;
}, { passive: true });
document.addEventListener('mouseout', e => {
if (!get('gifHover') || !_gifActiveCont) return;
const to = e.relatedTarget;
// If the mouse moved to another element still inside the pin wrapper, keep playing
if (to && _gifActiveCont.contains(to)) return;
pauseActiveGif();
}, { passive: true });
// ── Touch: tap to preview GIF on mobile ──────────────────────────
// First tap on a GIF pin starts playback; second tap (or tap elsewhere) stops it.
// Scrolling never accidentally triggers GIF playback.
let _gifTouchStartY = 0, _gifTouchScrolled = false;
document.addEventListener('touchstart', e => {
_gifTouchStartY = e.touches[0].clientY;
_gifTouchScrolled = false;
}, { passive: true });
document.addEventListener('touchmove', e => {
if (Math.abs(e.touches[0].clientY - _gifTouchStartY) > 8) _gifTouchScrolled = true;
}, { passive: true });
document.addEventListener('touchend', e => {
if (!get('gifHover') || _gifTouchScrolled) return;
// Don't interfere when the context menu is open
if (document.getElementById('pe-ctx-menu')) return;
const touch = e.changedTouches[0];
const el = document.elementFromPoint(touch.clientX, touch.clientY);
if (!el) return;
const pinWrapper = findGifContainer(el);
if (!pinWrapper) { pauseActiveGif(); return; }
const img = pinWrapper.querySelector(GIF_IMG_SEL)
|| (isMobileGifPin(pinWrapper) ? pinWrapper.querySelector('img') : null);
const gifUrl = img ? getGifSrcFromImg(img) : null;
if (!gifUrl) {
// No img-based GIF – check for a mobile video-based GIF
const vid = pinWrapper.querySelector('video');
if (vid) hydrateVideoSource(vid);
if (!vid || !isGifVideo(vid, pinWrapper)) { pauseActiveGif(); return; }
// Second tap on the same video GIF = stop
if (pinWrapper === _gifActiveCont) { pauseActiveGif(); return; }
pauseActiveGif();
_gifActiveCont = pinWrapper;
_gifActiveVid = vid;
vid.muted = true;
vid.loop = true;
vid.playsInline = true;
if (vid.readyState === 0) {
try { vid.load(); } catch (_) {}
}
try { vid.play(); } catch (_) {}
return;
}
// Second tap on the same GIF pin = stop
if (pinWrapper === _gifActiveCont) { pauseActiveGif(); return; }
pauseActiveGif();
_gifActiveImg = img;
_gifOrigSrc = img.src;
_gifOrigSrcset = img.getAttribute('srcset');
_gifActiveCont = pinWrapper;
img.removeAttribute('srcset');
img.src = gifUrl;
}, { passive: true });
}
// ═══════════════════════════════════════════════════════════════════
// MODULE: GIF AUTO-PLAY (viewport-based)
// ═══════════════════════════════════════════════════════════════════
// Uses IntersectionObserver to play all GIFs currently visible on
// screen and stop them when scrolled out of view to save CPU/memory.
let _gifAutoIO = null; // IntersectionObserver
let _gifAutoMO = null; // MutationObserver for new pins
function startGifInView(wrapper) {
// ── img-based GIF (desktop + most mobile, including mobile JPEG-srcset GIFs) ──
const img = wrapper.querySelector(GIF_IMG_SEL)
|| (isMobileGifPin(wrapper) ? wrapper.querySelector('img') : null);
if (img && !img.__peAutoPlaying) {
const gifUrl = getGifSrcFromImg(img);
if (gifUrl) {
img.__peAutoOrigSrc = img.src;
img.__peAutoOrigSrcset = img.getAttribute('srcset');
img.removeAttribute('srcset');
img.src = gifUrl;
img.__peAutoPlaying = true;
return;
}
}
// ── video-based GIF (mobile) ──
const vid = wrapper.querySelector('video');
if (vid && !vid.__peAutoPlaying) {
hydrateVideoSource(vid);
if (isGifVideo(vid, wrapper)) {
vid.__peAutoPlaying = true;
vid.muted = true;
vid.loop = true;
vid.playsInline = true;
if (vid.readyState === 0) {
try { vid.load(); } catch (_) {}
}
try { vid.play(); } catch (_) {}
}
}
}
function stopGifInView(wrapper) {
wrapper.querySelectorAll('img').forEach(img => {
if (!img.__peAutoPlaying) return;
// Don't interfere if hover is currently managing this img
if (img === _gifActiveImg) { img.__peAutoPlaying = false; return; }
if (img.__peAutoOrigSrcset) img.setAttribute('srcset', img.__peAutoOrigSrcset);
if (img.__peAutoOrigSrc) img.src = img.__peAutoOrigSrc;
img.__peAutoPlaying = false;
});
// Stop video-based GIFs (mobile)
wrapper.querySelectorAll('video').forEach(vid => {
if (!vid.__peAutoPlaying) return;
vid.__peAutoPlaying = false;
if (vid === _gifActiveVid) return; // hover/tap is managing this video
try { vid.pause(); } catch (_) {}
});
}
function observeGifPins() {
if (!_gifAutoIO) return;
document.querySelectorAll(GIF_PIN_CONTAINER_SEL).forEach(wrapper => {
if (wrapper.__peAutoObs) return;
// Detect img-based GIF, video-based GIF, or mobile JPEG-srcset GIF
const hasGifImg = !!wrapper.querySelector(GIF_IMG_SEL);
const hasGifVid = (() => {
const vid = wrapper.querySelector('video');
if (!vid) return false;
if (vid.__peGifVid) return true; // already confirmed as a GIF video
return isGifVideo(vid, wrapper);
})();
const hasMobileGif = !hasGifImg && !hasGifVid && isMobileGifPin(wrapper);
if (!hasGifImg && !hasGifVid && !hasMobileGif) return;
wrapper.__peAutoObs = true;
_gifAutoIO.observe(wrapper);
});
}
function initGifAutoPlay() {
if (_gifAutoIO) return;
_gifAutoIO = new IntersectionObserver(entries => {
// Skip when feature is off or tab is hidden (avoids playing on inactive tabs)
if (!get('gifAutoPlay') || document.hidden) return;
entries.forEach(entry => {
if (entry.isIntersecting) startGifInView(entry.target);
else stopGifInView(entry.target);
});
}, { threshold: 0.1 });
observeGifPins();
_gifAutoMO = new MutationObserver(observeGifPins);
_gifAutoMO.observe(document.documentElement, { childList: true, subtree: true });
}
function stopGifAutoPlay() {
if (_gifAutoIO) { _gifAutoIO.disconnect(); _gifAutoIO = null; }
if (_gifAutoMO) { _gifAutoMO.disconnect(); _gifAutoMO = null; }
document.querySelectorAll(GIF_PIN_CONTAINER_SEL).forEach(wrapper => {
stopGifInView(wrapper);
wrapper.__peAutoObs = false;
});
}
// Pause all auto-playing GIFs when the tab/window is hidden to save resources,
// and resume them when the user comes back.
document.addEventListener('visibilitychange', () => {
if (!get('gifAutoPlay')) return;
if (document.hidden) {
document.querySelectorAll(GIF_PIN_CONTAINER_SEL).forEach(stopGifInView);
} else if (_gifAutoIO) {
// Re-start GIFs that are still in the viewport
document.querySelectorAll(GIF_PIN_CONTAINER_SEL).forEach(wrapper => {
if (!wrapper.__peAutoObs) return;
const r = wrapper.getBoundingClientRect();
if (r.top < window.innerHeight && r.bottom > 0) startGifInView(wrapper);
});
}
});
// ═══════════════════════════════════════════════════════════════════
// MODULE: DECLUTTER (no ads, no shopping, no blank spaces)
// ═══════════════════════════════════════════════════════════════════
// Collapses unwanted elements to zero size instead of display:none
// so the masonry grid reflows cleanly with no empty slots.
// Sets grid-auto-flow:dense on pin-list containers once per container.
function collapseEl(el) {
if (!el) return;
el.style.setProperty('height', '0', 'important');
el.style.setProperty('width', '0', 'important');
el.style.setProperty('margin', '0', 'important');
el.style.setProperty('padding', '0', 'important');
el.style.setProperty('border', 'none', 'important');
el.style.setProperty('overflow', 'hidden', 'important');
el.style.setProperty('opacity', '0', 'important');
el.style.setProperty('min-height', '0', 'important');
el.style.setProperty('min-width', '0', 'important');
// Make the parent grid fill the gap
const grid = el.closest('div[role="list"]');
if (grid && !grid.dataset.peDense) {
grid.style.setProperty('grid-auto-flow', 'dense', 'important');
grid.dataset.peDense = '1';
}
}
function isDeclutterPin(pin) {
// Sponsored
if (pin.querySelector('div[title="Sponsored"]')) return true;
// Shoppable Pin indicator
if (pin.querySelector('[aria-label="Shoppable Pin indicator"]')) return true;
// Shopping cards / "Shop" headings
const h2 = pin.querySelector('h2#comments-heading');
if (h2 && h2.textContent.trim().toLowerCase().startsWith('shop')) return true;
const aLink = pin.querySelector('a');
if (aLink && (aLink.getAttribute('aria-label') || '').toLowerCase().startsWith('shop')) return true;
// Featured boards / window shopping promos
const text = pin.textContent.trim().toLowerCase();
if (text.startsWith('explore featured boards')) return true;
if (text.startsWith('still window shopping')) return true;
// Quiz posts
if (/\bquiz\b/i.test(pin.textContent)) return true;
// Deleted / unavailable pins
if (pin.querySelector('[data-test-id="unavailable-pin"]')) return true;
// Product cards with price tags (individual Shop the look items)
if (pin.querySelector('[data-test-id="product-price-text"]')) return true;
if (pin.querySelector('[data-test-id="pincard-product-with-link"]')) return true;
return false;
}
function filterPins(container) {
if (!get('declutter')) return;
container.querySelectorAll('div[role="listitem"]').forEach(pin => {
if (!pin.__peDecluttered && isDeclutterPin(pin)) {
pin.__peDecluttered = true;
collapseEl(pin);
}
});
}
function removeDeclutterOneoffs() {
if (!get('declutter')) return;
// Shop tab on board tools bar
document.querySelectorAll('[data-test-id="board-tools"] [data-test-id="Shop"]')
.forEach(el => collapseEl(el.closest('div')));
// Shop-by / sf-header banners
document.querySelectorAll('[data-test-id="sf-header-heading"]').forEach(el => {
collapseEl(el.closest('div[role="listitem"]') || el.parentElement);
});
// Download upsell popover
document.querySelectorAll('[data-test-id="post-download-upsell-popover"]')
.forEach(collapseEl);
// Ad blocker modal
document.querySelectorAll('div[aria-label="Ad blocker modal"]').forEach(el => {
collapseEl(el);
if (document.body.style.overflow === 'hidden') document.body.style.overflow = '';
});
// Explore-tab notification badge
const todayTab = document.querySelector('a[data-test-id="today-tab"]');
if (todayTab) {
const iconWrap = todayTab.closest('div');
const sidebarItem = iconWrap?.parentElement?.parentElement;
const badge = sidebarItem?.parentElement?.querySelector('.MIw[style*="pointer-events: none"]');
if (badge) collapseEl(badge);
}
// Pin card notification badges (the floating status dot on pins)
document.querySelectorAll('[aria-label="Notifications"][role="status"]').forEach(el => {
collapseEl(el.parentElement || el);
});
// Shopping spotlight carousel section
document.querySelectorAll('[data-test-id="carousel-bubble-wrapper-shopping_spotlight"]').forEach(el => {
collapseEl(el.closest('div[role="listitem"]') || el.parentElement?.parentElement?.parentElement || el.parentElement || el);
});
// Curated spotlight section (search page immersive header carousel)
document.querySelectorAll('[data-test-id="search-story-suggestions-container"]:has([data-test-id="search-suggestion-curated-board-bubble"])').forEach(el => {
collapseEl(el);
});
// Pin action bar: "Read it" / "Visit site" inline button on mobile closeup
document.querySelectorAll('[data-test-id="pin-action-bar-container"]').forEach(el => {
collapseEl(el.parentElement || el);
});
// Shop similar / Shop the look sections on pin closeup
document.querySelectorAll(
'[data-test-id="ShopTheLookSimilarProducts"],' +
'[data-test-id="visual-search-shopping-bar"],' +
'[data-test-id="related-products"],' +
'[data-test-id="ShopTheLookAnnotations"]'
).forEach(el => {
collapseEl(el.closest('div[role="listitem"]') || el.parentElement || el);
});
// Shop the look carousel grid items (full-width shopping module in feed)
document.querySelectorAll('[data-test-id="shopping-module"]').forEach(el => {
collapseEl(el.closest('div[role="listitem"]') || el.closest('[data-grid-item="true"]') || el.parentElement || el);
});
}
let _declutterListObs = null;
function initDeclutter() {
if (!get('declutter')) return;
// Observe the pin grid list(s) for new list items
function attachListObserver(listEl) {
if (listEl.__peDeclutterObs) return;
listEl.__peDeclutterObs = true;
filterPins(listEl);
const onMutate = IS_MOBILE ? debounce(() => filterPins(listEl), 200) : () => filterPins(listEl);
new MutationObserver(onMutate)
.observe(listEl, { childList: true, subtree: true });
}
// Attach to any already-present lists
document.querySelectorAll('div[role="list"]').forEach(attachListObserver);
removeDeclutterOneoffs();
// Watch for new lists added by SPA navigation or lazy load
if (_declutterListObs) return;
_declutterListObs = new MutationObserver(() => {
document.querySelectorAll('div[role="list"]').forEach(attachListObserver);
removeDeclutterOneoffs();
});
_declutterListObs.observe(document.documentElement, { childList: true, subtree: true });
}
// ═══════════════════════════════════════════════════════════════════
// MODULE: REMOVE VIDEOS (collapse to avoid blank spaces)
// ═══════════════════════════════════════════════════════════════════
// Detects video pins via their duration label (PinTypeIdentifier)
// and collapses them using the same technique as Declutter to
// avoid blank spaces in the grid.
function isVideoPin(pin) {
// PinTypeIdentifier badge appears on both GIFs and videos — check its text
const badge = pin.querySelector('[data-test-id="PinTypeIdentifier"]');
if (badge) {
const t = badge.textContent.trim().toLowerCase();
if (t === 'gif' || t.includes('animated')) return false; // it's a GIF, not a video
if (t === 'video' || t.includes('watch')) return true;
}
// <video> elements: GIFs use i.pinimg.com, real videos use v.pinimg.com
const vid = pin.querySelector('video');
if (vid) {
const src = vid.src
|| (vid.querySelector('source') && vid.querySelector('source').src)
|| '';
if (/v\.pinimg\.com/i.test(src)) return true; // Pinterest-hosted video
if (/i\.pinimg\.com/i.test(src)) return false; // GIF rendered as video
// Unknown CDN (e.g. YouTube embed inside an iframe) — treat as video
if (src) return true;
}
// Explicit video-only indicators
if (pin.querySelector('[data-test-id="video-pin-indicator"], [data-test-id="PinVideoIdentifier"]')) return true;
return false;
}
function filterVideoPins(container) {
if (!get('removeVideos')) return;
container.querySelectorAll('div[role="listitem"]').forEach(pin => {
if (!pin.__peVideoRemoved && isVideoPin(pin)) {
pin.__peVideoRemoved = true;
collapseEl(pin);
}
});
}
let _removeVideosObs = null;
function initRemoveVideos() {
if (!get('removeVideos') || _removeVideosObs) return;
function attachListObserver(listEl) {
if (listEl.__peVideoObs) return;
listEl.__peVideoObs = true;
filterVideoPins(listEl);
const onMutate = IS_MOBILE ? debounce(() => filterVideoPins(listEl), 200) : () => filterVideoPins(listEl);
new MutationObserver(onMutate)
.observe(listEl, { childList: true, subtree: true });
}
document.querySelectorAll('div[role="list"]').forEach(attachListObserver);
_removeVideosObs = new MutationObserver(() => {
document.querySelectorAll('div[role="list"]').forEach(attachListObserver);
});
_removeVideosObs.observe(document.documentElement, { childList: true, subtree: true });
}
// ═══════════════════════════════════════════════════════════════════
// MODULE: HIDE SHOP POSTS (TeePublic, Redbubble, AliExpress, etc.)
// ═══════════════════════════════════════════════════════════════════
const SHOP_DOMAINS = [
'teepublic.com', 'redbubble.com',
'aliexpress.com', 'aliexpress.us', 'aliexpress.ru',
'amazon.com', 'amazon.co.uk', 'amazon.ca', 'amazon.com.au', 'amazon.de',