- Joined
- Nov 26, 2018
You could totally use https://git.kiwifarms.st/ for your code btw
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
// ==UserScript==
// @name Confetti
// @match https://kiwifarms.st/*
// @match https://kiwifarmsaaf4t2h7gc3dfc5ojhmqruw2nit3uejrpiagrxeuxiyxcyd.onion/*
// ==/UserScript==
if(!window.confetti) {
// Original file: https://no-cookie.kiwifarmsaaf4t2h7gc3dfc5ojhmqruw2nit3uejrpiagrxeuxiyxcyd.onion/public/junk/confetti.1.9.4.browser.min.js?2
/**
* Minified by jsDelivr using Terser v5.39.0.
* Original file: /npm/canvas-confetti@1.9.4/dist/confetti.browser.js
*
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
*/
!function(t,e){!function t(e,a,n,r){var o=!!(e.Worker&&e.Blob&&e.Promise&&e.OffscreenCanvas&&e.OffscreenCanvasRenderingContext2D&&e.HTMLCanvasElement&&e.HTMLCanvasElement.prototype.transferControlToOffscreen&&e.URL&&e.URL.createObjectURL),i="function"==typeof Path2D&&"function"==typeof DOMMatrix,l=function(){if(!e.OffscreenCanvas)return!1;try{var t=new OffscreenCanvas(1,1),a=t.getContext("2d");a.fillRect(0,0,1,1);var n=t.transferToImageBitmap();a.createPattern(n,"no-repeat")}catch(t){return!1}return!0}();function s(){}function c(t){var n=a.exports.Promise,r=void 0!==n?n:e.Promise;return"function"==typeof r?new r(t):(t(s,s),null)}var h,f,u,d,m,g,p,b,M,v,y,w=(h=l,f=new Map,{transform:function(t){if(h)return t;if(f.has(t))return f.get(t);var e=new OffscreenCanvas(t.width,t.height);return e.getContext("2d").drawImage(t,0,0),f.set(t,e),e},clear:function(){f.clear()}}),x=(m=Math.floor(1e3/60),g={},p=0,"function"==typeof requestAnimationFrame&&"function"==typeof cancelAnimationFrame?(u=function(t){var e=Math.random();return g[e]=requestAnimationFrame((function a(n){p===n||p+m-1<n?(p=n,delete g[e],t()):g[e]=requestAnimationFrame(a)})),e},d=function(t){g[t]&&cancelAnimationFrame(g[t])}):(u=function(t){return setTimeout(t,m)},d=function(t){return clearTimeout(t)}),{frame:u,cancel:d}),C=(v={},function(){if(b)return b;if(!n&&o){var e=["var CONFETTI, SIZE = {}, module = {};","("+t.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join("\n");try{b=new Worker(URL.createObjectURL(new Blob([e])))}catch(t){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("🎊 Could not load worker",t),null}!function(t){function e(e,a){t.postMessage({options:e||{},callback:a})}t.init=function(e){var a=e.transferControlToOffscreen();t.postMessage({canvas:a},[a])},t.fire=function(a,n,r){if(M)return e(a,null),M;var o=Math.random().toString(36).slice(2);return M=c((function(n){function i(e){e.data.callback===o&&(delete v[o],t.removeEventListener("message",i),M=null,w.clear(),r(),n())}t.addEventListener("message",i),e(a,o),v[o]=i.bind(null,{data:{callback:o}})}))},t.reset=function(){for(var e in t.postMessage({reset:!0}),v)v[e](),delete v[e]}}(b)}return b}),I={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function T(t,e,a){return function(t,e){return e?e(t):t}(t&&null!=t[e]?t[e]:I[e],a)}function E(t){return t<0?0:Math.floor(t)}function P(t){return parseInt(t,16)}function S(t){return t.map(O)}function O(t){var e=String(t).replace(/[^0-9a-f]/gi,"");return e.length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),{r:P(e.substring(0,2)),g:P(e.substring(2,4)),b:P(e.substring(4,6))}}function k(t){t.width=document.documentElement.clientWidth,t.height=document.documentElement.clientHeight}function B(t){var e=t.getBoundingClientRect();t.width=e.width,t.height=e.height}function F(t,e){e.x+=Math.cos(e.angle2D)*e.velocity+e.drift,e.y+=Math.sin(e.angle2D)*e.velocity+e.gravity,e.velocity*=e.decay,e.flat?(e.wobble=0,e.wobbleX=e.x+10*e.scalar,e.wobbleY=e.y+10*e.scalar,e.tiltSin=0,e.tiltCos=0,e.random=1):(e.wobble+=e.wobbleSpeed,e.wobbleX=e.x+10*e.scalar*Math.cos(e.wobble),e.wobbleY=e.y+10*e.scalar*Math.sin(e.wobble),e.tiltAngle+=.1,e.tiltSin=Math.sin(e.tiltAngle),e.tiltCos=Math.cos(e.tiltAngle),e.random=Math.random()+2);var a=e.tick++/e.totalTicks,n=e.x+e.random*e.tiltCos,r=e.y+e.random*e.tiltSin,o=e.wobbleX+e.random*e.tiltCos,l=e.wobbleY+e.random*e.tiltSin;if(t.fillStyle="rgba("+e.color.r+", "+e.color.g+", "+e.color.b+", "+(1-a)+")",t.beginPath(),i&&"path"===e.shape.type&&"string"==typeof e.shape.path&&Array.isArray(e.shape.matrix))t.fill(function(t,e,a,n,r,o,i){var l=new Path2D(t),s=new Path2D;s.addPath(l,new DOMMatrix(e));var c=new Path2D;return c.addPath(s,new DOMMatrix([Math.cos(i)*r,Math.sin(i)*r,-Math.sin(i)*o,Math.cos(i)*o,a,n])),c}(e.shape.path,e.shape.matrix,e.x,e.y,.1*Math.abs(o-n),.1*Math.abs(l-r),Math.PI/10*e.wobble));else if("bitmap"===e.shape.type){var s=Math.PI/10*e.wobble,c=.1*Math.abs(o-n),h=.1*Math.abs(l-r),f=e.shape.bitmap.width*e.scalar,u=e.shape.bitmap.height*e.scalar,d=new DOMMatrix([Math.cos(s)*c,Math.sin(s)*c,-Math.sin(s)*h,Math.cos(s)*h,e.x,e.y]);d.multiplySelf(new DOMMatrix(e.shape.matrix));var m=t.createPattern(w.transform(e.shape.bitmap),"no-repeat");m.setTransform(d),t.globalAlpha=1-a,t.fillStyle=m,t.fillRect(e.x-f/2,e.y-u/2,f,u),t.globalAlpha=1}else if("circle"===e.shape)t.ellipse?t.ellipse(e.x,e.y,Math.abs(o-n)*e.ovalScalar,Math.abs(l-r)*e.ovalScalar,Math.PI/10*e.wobble,0,2*Math.PI):function(t,e,a,n,r,o,i,l,s){t.save(),t.translate(e,a),t.rotate(o),t.scale(n,r),t.arc(0,0,1,i,l,s),t.restore()}(t,e.x,e.y,Math.abs(o-n)*e.ovalScalar,Math.abs(l-r)*e.ovalScalar,Math.PI/10*e.wobble,0,2*Math.PI);else if("star"===e.shape)for(var g=Math.PI/2*3,p=4*e.scalar,b=8*e.scalar,M=e.x,v=e.y,y=5,x=Math.PI/y;y--;)M=e.x+Math.cos(g)*b,v=e.y+Math.sin(g)*b,t.lineTo(M,v),g+=x,M=e.x+Math.cos(g)*p,v=e.y+Math.sin(g)*p,t.lineTo(M,v),g+=x;else t.moveTo(Math.floor(e.x),Math.floor(e.y)),t.lineTo(Math.floor(e.wobbleX),Math.floor(r)),t.lineTo(Math.floor(o),Math.floor(l)),t.lineTo(Math.floor(n),Math.floor(e.wobbleY));return t.closePath(),t.fill(),e.tick<e.totalTicks}function A(t,a){var i,l=!t,s=!!T(a||{},"resize"),h=!1,f=T(a,"disableForReducedMotion",Boolean),u=o&&!!T(a||{},"useWorker")?C():null,d=l?k:B,m=!(!t||!u)&&!!t.__confetti_initialized,g="function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion)").matches;function p(e,a,o){for(var l,s,h,f,u,m=T(e,"particleCount",E),g=T(e,"angle",Number),p=T(e,"spread",Number),b=T(e,"startVelocity",Number),M=T(e,"decay",Number),v=T(e,"gravity",Number),y=T(e,"drift",Number),C=T(e,"colors",S),I=T(e,"ticks",Number),P=T(e,"shapes"),O=T(e,"scalar"),k=!!T(e,"flat"),B=function(t){var e=T(t,"origin",Object);return e.x=T(e,"x",Number),e.y=T(e,"y",Number),e}(e),A=m,R=[],N=t.width*B.x,z=t.height*B.y;A--;)R.push((l={x:N,y:z,angle:g,spread:p,startVelocity:b,color:C[A%C.length],shape:P[(f=0,u=P.length,Math.floor(Math.random()*(u-f))+f)],ticks:I,decay:M,gravity:v,drift:y,scalar:O,flat:k},s=void 0,h=void 0,s=l.angle*(Math.PI/180),h=l.spread*(Math.PI/180),{x:l.x,y:l.y,wobble:10*Math.random(),wobbleSpeed:Math.min(.11,.1*Math.random()+.05),velocity:.5*l.startVelocity+Math.random()*l.startVelocity,angle2D:-s+(.5*h-Math.random()*h),tiltAngle:(.5*Math.random()+.25)*Math.PI,color:l.color,shape:l.shape,tick:0,totalTicks:l.ticks,decay:l.decay,drift:l.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:3*l.gravity,ovalScalar:.6,scalar:l.scalar,flat:l.flat}));return i?i.addFettis(R):(i=function(t,e,a,o,i){var l,s,h=e.slice(),f=t.getContext("2d"),u=c((function(e){function c(){l=s=null,f.clearRect(0,0,o.width,o.height),w.clear(),i(),e()}l=x.frame((function e(){!n||o.width===r.width&&o.height===r.height||(o.width=t.width=r.width,o.height=t.height=r.height),o.width||o.height||(a(t),o.width=t.width,o.height=t.height),f.clearRect(0,0,o.width,o.height),(h=h.filter((function(t){return F(f,t)}))).length?l=x.frame(e):c()})),s=c}));return{addFettis:function(t){return h=h.concat(t),u},canvas:t,promise:u,reset:function(){l&&x.cancel(l),s&&s()}}}(t,R,d,a,o),i.promise)}function b(a){var n=f||T(a,"disableForReducedMotion",Boolean),r=T(a,"zIndex",Number);if(n&&g)return c((function(t){t()}));l&&i?t=i.canvas:l&&!t&&(t=function(t){var e=document.createElement("canvas");return e.style.position="fixed",e.style.top="0px",e.style.left="0px",e.style.pointerEvents="none",e.style.zIndex=t,e}(r),document.body.appendChild(t)),s&&!m&&d(t);var o={width:t.width,height:t.height};function b(){if(u){var e={getBoundingClientRect:function(){if(!l)return t.getBoundingClientRect()}};return d(e),void u.postMessage({resize:{width:e.width,height:e.height}})}o.width=o.height=null}function M(){i=null,s&&(h=!1,e.removeEventListener("resize",b)),l&&t&&(document.body.contains(t)&&document.body.removeChild(t),t=null,m=!1)}return u&&!m&&u.init(t),m=!0,u&&(t.__confetti_initialized=!0),s&&!h&&(h=!0,e.addEventListener("resize",b,!1)),u?u.fire(a,o,M):p(a,o,M)}return b.reset=function(){u&&u.reset(),i&&i.reset()},b}function R(){return y||(y=A(null,{useWorker:!0,resize:!0})),y}a.exports=function(){return R().apply(this,arguments)},a.exports.reset=function(){R().reset()},a.exports.create=A,a.exports.shapeFromPath=function(t){if(!i)throw new Error("path confetti are not supported in this browser");var e,a;"string"==typeof t?e=t:(e=t.path,a=t.matrix);var n=new Path2D(e),r=document.createElement("canvas").getContext("2d");if(!a){for(var o,l,s=1e3,c=s,h=s,f=0,u=0,d=0;d<s;d+=2)for(var m=0;m<s;m+=2)r.isPointInPath(n,d,m,"nonzero")&&(c=Math.min(c,d),h=Math.min(h,m),f=Math.max(f,d),u=Math.max(u,m));o=f-c,l=u-h;var g=Math.min(10/o,10/l);a=[g,0,0,g,-Math.round(o/2+c)*g,-Math.round(l/2+h)*g]}return{type:"path",path:e,matrix:a}},a.exports.shapeFromText=function(t){var e,a=1,n="#000000",r='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';"string"==typeof t?e=t:(e=t.text,a="scalar"in t?t.scalar:a,r="fontFamily"in t?t.fontFamily:r,n="color"in t?t.color:n);var o=10*a,i=o+"px "+r,l=new OffscreenCanvas(o,o),s=l.getContext("2d");s.font=i;var c=s.measureText(e),h=Math.ceil(c.actualBoundingBoxRight+c.actualBoundingBoxLeft),f=Math.ceil(c.actualBoundingBoxAscent+c.actualBoundingBoxDescent),u=c.actualBoundingBoxLeft+2,d=c.actualBoundingBoxAscent+2;h+=4,f+=4,(s=(l=new OffscreenCanvas(h,f)).getContext("2d")).font=i,s.fillStyle=n,s.fillText(e,u,d);var m=1/a;return{type:"bitmap",bitmap:l.transferToImageBitmap(),matrix:[m,0,0,m,-h*m/2,-f*m/2]}}}(function(){return void 0!==t?t:"undefined"!=typeof self?self:this||{}}(),e,!1),t.confetti=e.exports}(window,{});
//# sourceMappingURL=/sm/cad7c3ca296fcad2eda2459178be2ed4967f4098c8e8e20900f845e89fca8f7d.map
}
(function() {
function randomInRange(min, max) {
return Math.random() * (max - min) + min;
}
const canvas = document.getElementById('confetti');
const fireConfetti = confetti.create(canvas, {
resize: true,
useWorker: true
});
window.addEventListener('click', function(event) {
fireConfetti({
colors: ['#FFFFFF', '#0039A6', '#FF6319'],
angle: randomInRange(55, 125),
spread: randomInRange(20, 50),
particleCount: Math.floor(randomInRange(5, 11)),
startVelocity: 25,
origin: {
x: event.clientX / window.innerWidth,
y: event.clientY / window.innerHeight
}
});
});
})();
PSA for phonefags: change ".message-userExtras" to ".message-userDetails"Farmer's Almanac
Too many exceptional meatballs to keep track of? The Farmer's Almanac is here to mark your persons of interest with an indelible niggercattle branding iron.
- Add inline notes to every post or keep extended details on the user page
- Colored highlights for exceptionally colored individuals
- Private profiles and HTML are supported
// ==UserScript==
// @name Hidden Member Info And Prev/Next
// @match https://kiwifarms.st/members/*
// @match https://kiwifarmsaaf4t2h7gc3dfc5ojhmqruw2nit3uejrpiagrxeuxiyxcyd.onion/members/*
// ==/UserScript==
async function fetchHiddenProfileHTML(id) {
const csrf = document.documentElement.getAttribute("data-csrf");
const profileUrl = `/members/${id}/?tooltip=true&_xfResponseType=json&_xfWithData=1&_xfRequestUri=/members/${id}&_xfToken=${csrf}`;
const response = await fetch(profileUrl);
if (!response.ok) {
return "<i>Profile fetch failed</i>";
}
const result = await response.json();
if (result.status != "ok") {
return "<i>Profile fetch failed</i>";
}
return result.html.content;
}
function renderMemberPage(id) {
let container = document.querySelector(".memberHeader > .memberHeader-main .memberHeader-actionTop .buttonGroup");
if (!container) {
// Hidden profile: New block for Prev/Next buttons
let block = document.createElement("div");
block.classList.add("blockMessage");
document.querySelector(".p-body-pageContent").prepend(block);
container = block;
// Fetch info from tooltip endpoint
fetchHiddenProfileHTML(id).then(profileHTML => {
let block = document.createElement("div");
block.classList.add("blockMessage");
block.innerHTML = profileHTML;
container.appendChild(block);
});
}
const prev = document.createElement("a");
const next = document.createElement("a");
prev.classList.add("button", "button--link", "pageNav-jump", "pageNav-jump--prev");
next.classList.add("button", "button--link", "pageNav-jump", "pageNav-jump--next");
prev.innerText = "Prev";
next.innerText = "Next";
prev.style.marginLeft = "2px";
next.style.marginLeft = "2px";
prev.setAttribute("href", `/members/${id-1}`);
next.setAttribute("href", `/members/${id+1}`);
prev.setAttribute("data-xf-key", "ArrowLeft"); // Hotkeys (fetch above breaks hotkeys if this function is made async)
next.setAttribute("data-xf-key", "ArrowRight");
if (id > 1) {
container.appendChild(prev);
}
if (id < Infinity) {
container.appendChild(next);
}
}
(function() {
let id = parseInt(document.location.pathname.split(".").at(-1)); // /members/name.${id}/
if (!id) {
id = parseInt(document.location.pathname.split("/").at(2)); // /members/${id}/
}
if (id) {
renderMemberPage(id);
}
})();
Reposting this hereCreated because It makes computer 1% more efficient.
KIWI-DLP adds a button/extension to Chromium browsers for downloading the video or audio from the page you're on, using yt-dlp. In the popup you can:
- Choose Audio or Video. The formats (e.g. FLAC and MP4) are set in config.json.
- Clip a section by typing start and end times, or by pressing Now to use the player's current position.
- Choose whether to embed metadata (title, artist, date) and the thumbnail as cover art.
- Choose whether to download a whole playlist or just the current video.
- It works on any site yt-dlp supports, including YouTube, Rumble and Odysee, and Twitter/X.
// ==UserScript==
// @name Everyone is banned - kiwifarms.st
// @match https://kiwifarms.st/threads/*
// @match https://kiwifarms.st/direct-messages/*
// ==/UserScript==
document.querySelectorAll('span[itemprop="name"]').forEach(elem => {
if (elem.parentElement?.hasAttribute('class')) {
elem.classList.add('class', 'username--style175')
}
});
// ==UserScript==
// @name hampter replacer
// @version 1.0
// @description fuck u
// @author dick brain
// @match https://kiwifarms.st/*
// @match https://kiwifarms.net/*
// @grant none
// @run-at document-start
// ==/UserScript==
const newImage = 'https://kiwifarms.st/attachments/1793075192969-png.9772790/';
function callback(_, observer) {
const hampter = document.querySelector('.avatar-u251718-m, .avatar-u251718-l, .avatar-u251718-s');
if (hampter) {
console.log(hampter);
hampter.outerHTML = `<img src="${newImage}">`;
// observer.disconnect();
}
}
new MutationObserver(callback).observe(document, {
childList: !0,
subtree: !0,
});
// ==UserScript==
// @name KF Random Thread Button
// @version 2026-11-09
// @description Adds a button to the KF front page that takes you to a random thread.
// @match https://kiwifarms.net/
// @match https://kiwifarms.st/
// @match https://kiwifarmsaaf4t2h7gc3dfc5ojhmqruw2nit3uejrpiagrxeuxiyxcyd.onion/
// @icon https://www.google.com/s2/favicons?sz=64&domain=kiwifarms.net
// ==/UserScript==
(function() {
const BASE_URL = "https://kiwifarms.net/threads/"
const polThreadURL = document.querySelector('div[data-widget-key="new_political_thread"] a[href*="/threads/"]').getAttribute("href").split(".");
let polThreadID = parseInt(polThreadURL[1].replace("/", ""));
document.querySelector(".p-sectionLinks-list").appendChild(document.createElement("li")).insertAdjacentHTML("afterbegin", "<div class='p-navEl'><button id='newTab' class='p-navEl-link'>Random Thread</button></div>")
const newTab = document.querySelector("#newTab");
newTab.addEventListener("click", () => {
window.open(BASE_URL + Math.floor(Math.random() * (polThreadID + 1)));
});
})();
// ==UserScript==
// @name LibGen Highlight EPUB + English
// @match https://libgen.gl/*
// @grant none
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
const STYLE_ID = 'libgen-highlight-style';
function injectStyle() {
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement('style');
style.id = STYLE_ID;
style.textContent = `
tr.libgen-match {
background-color: #d4f7d4 !important;
outline: 2px solid #2ecc71;
outline-offset: -2px;
}
tr.libgen-match td {
background-color: #d4f7d4 !important;
}
`;
document.head.appendChild(style);
}
function processRows() {
const rows = document.querySelectorAll('#tablelibgen tbody tr');
rows.forEach((row) => {
const cells = row.querySelectorAll('td');
if (cells.length < 8) return;
// language = 4 extension = 7
const langText = cells[4]?.textContent.trim().toLowerCase() || '';
const extText = cells[7]?.textContent.trim().toLowerCase() || '';
const isEnglish = langText.includes('english');
const isEpub = extText.includes('epub');
if (isEnglish && isEpub) {
row.classList.add('libgen-match');
} else {
row.classList.remove('libgen-match');
}
});
}
function init() {
injectStyle();
processRows();
const table = document.querySelector('#tablelibgen');
if (table) {
const observer = new MutationObserver(() => {
processRows();
});
observer.observe(table, { childList: true, subtree: true });
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
// ==UserScript==
// @name KF Listening YouTube Playlist
// @namespace local.threadplaylist
// @version 1.5
// @description Collect every YouTube embed in a thread page into a playable playlist
// @grant GM_xmlhttpRequest
// @include /^https?:\/\/([^/]*\.)?kiwifarms\.[^/]+\/threads\/(what-are-you-listening-to-right-now\.)?159(\/.*)?$/
// @connect www.youtube.com
// @icon https://kiwifarms.net/favicon.ico
// @run-at document-idle
// ==/UserScript==
// apply to all threads:
// @include /^[^:]*?://([^/]*\.)?kiwifarms\.[^/]*?/threads/.*?$/
(() => {
'use strict';
// Only the wrapper's data attribute is read. In-post iframes are never touched.
const EMBED_SEL = '.bbMediaWrapper[data-media-site-id="youtube"]';
// ---------- title cache + oEmbed ----------
const TITLE_KEY = 'tp-titles-v1';
let titleCache = {};
try { titleCache = JSON.parse(localStorage.getItem(TITLE_KEY) || '{}'); } catch {}
let saveTimer = 0;
const saveCache = () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
try { localStorage.setItem(TITLE_KEY, JSON.stringify(titleCache)); } catch {}
}, 500);
};
const cleanTitle = s => s
.replace(/\s*[\[(]\s*(official|lyrics?|audio|hd|hq|remaster|music video|video)[^\])]*[\])]/gi, '')
.replace(/\s+/g, ' ')
.trim();
function fetchTitle(id) {
return new Promise(resolve => {
GM_xmlhttpRequest({
method: 'GET',
url: 'https://www.youtube.com/oembed?format=json&url=' +
encodeURIComponent('https://www.youtube.com/watch?v=' + id),
timeout: 10000,
onload: r => {
if (r.status === 200) {
try {
const j = JSON.parse(r.responseText);
return resolve({ title: j.title, author: j.author_name });
} catch {}
}
if ([401, 403, 404].includes(r.status)) return resolve({ dead: r.status });
resolve(null);
},
onerror: () => resolve(null),
ontimeout: () => resolve(null),
});
});
}
async function resolveTitles(items) {
const queue = items.filter(it => !titleCache[it.id]);
const worker = async () => {
while (queue.length) {
const it = queue.shift();
const t = await fetchTitle(it.id);
if (!t) continue;
titleCache[it.id] = t;
saveCache();
if (t.title) it.label = cleanTitle(t.title);
if (playlist[index] === it) $('#tp-now').textContent = it.label;
scheduleRender();
}
};
await Promise.all([worker(), worker()]);
}
const isDead = it => !!titleCache[it.id]?.dead;
// ---------- label extraction (fallback from post text) ----------
const clean = s => s.replace(/\s+/g, ' ').trim();
function collectLine(start, dir) {
const prop = dir < 0 ? 'previousSibling' : 'nextSibling';
const parts = [];
let started = false;
for (let n = start; n; n = n[prop]) {
if (n.nodeType === 1 &&
(n.matches('.bbMediaWrapper, blockquote, .bbCodeBlock') ||
n.querySelector('.bbMediaWrapper'))) break;
if (n.nodeName === 'BR') {
if (started) break;
continue;
}
const t = n.textContent;
if (!t || !t.trim()) {
if (started) parts[dir < 0 ? 'unshift' : 'push'](t);
continue;
}
started = true;
parts[dir < 0 ? 'unshift' : 'push'](t);
}
return clean(parts.join(''));
}
function labelFor(el, wrapper) {
if (!wrapper) return '';
let node = el;
while (node && node.parentNode !== wrapper) node = node.parentNode;
if (!node) return '';
return collectLine(node.previousSibling, -1) || collectLine(node.nextSibling, 1);
}
// ---------- scrape (runs only on click / rescan) ----------
function scrape() {
const seen = new Set();
const items = [];
document.querySelectorAll(EMBED_SEL).forEach(el => {
const id = el.dataset.mediaKey;
if (!id || seen.has(id)) return;
seen.add(id);
const postLabel = labelFor(el, el.closest('.bbWrapper'));
const cached = titleCache[id]?.title;
items.push({
id,
label: cached ? cleanTitle(cached) : (postLabel || id),
article: el.closest('article.message, .message'), // the post, not the embed
});
});
return items;
}
// ---------- like helpers ----------
const likedPosts = new Set();
const likeLink = it => it.article?.querySelector('.actionBar-action--reaction') || null;
function postId(it) {
const a = likeLink(it);
const m = a && a.getAttribute('href').match(/\/posts\/(\d+)\//);
return m ? m[1] : null;
}
function isLiked(it) {
const a = likeLink(it);
if (!a) return false;
const pid = postId(it);
return (pid && likedPosts.has(pid)) ||
a.classList.contains('has-reaction') ||
!!it.article.querySelector('.reactionsBar .literally-my-reaction');
}
function like(it) {
const a = likeLink(it);
if (!a || isLiked(it)) return; // never toggle an existing reaction off
const pid = postId(it);
if (pid) likedPosts.add(pid);
a.click();
setTimeout(() => {
if (pid && !a.classList.contains('has-reaction')) likedPosts.delete(pid);
renderList();
}, 1500);
renderList();
}
// ---------- state ----------
let playlist = [];
let index = -1;
let shuffle = false;
let follow = true;
let ready = false;
let errorStreak = 0;
let lastPlay = 0;
// ---------- styles ----------
const css = document.createElement('style');
css.textContent = `
#tp-btn{position:fixed;right:16px;bottom:16px;z-index:99999;padding:8px 14px;
background:#c00;color:#fff;border:0;border-radius:6px;cursor:pointer;font:600 13px sans-serif}
#tp-panel{position:fixed;right:16px;bottom:16px;z-index:100000;width:360px;max-height:80vh;
display:none;flex-direction:column;background:#181818;color:#eee;border:1px solid #444;
border-radius:8px;font:13px sans-serif;box-shadow:0 4px 24px #000a}
#tp-panel.open{display:flex}
#tp-head{display:flex;align-items:center;justify-content:space-between;padding:6px 10px;background:#222;border-radius:8px 8px 0 0}
#tp-player{width:100%;aspect-ratio:16/9;background:#000;border:0;display:block}
#tp-ctrl{display:flex;gap:6px;padding:6px 10px;align-items:center}
#tp-ctrl button,#tp-head button{background:#333;color:#eee;border:1px solid #555;border-radius:4px;
padding:3px 9px;cursor:pointer}
#tp-ctrl button.on{background:#c00}
#tp-now{flex:1;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;opacity:.8}
#tp-list{overflow-y:auto;margin:0;padding:0;list-style:none;border-top:1px solid #333}
#tp-list li{display:flex;gap:6px;padding:5px 10px;cursor:pointer;border-bottom:1px solid #2a2a2a}
#tp-list li:hover{background:#2a2a2a}
#tp-list li.cur{background:#3a1010;font-weight:600}
#tp-list li.dead .t{text-decoration:line-through;opacity:.4}
#tp-list li .n{opacity:.5;min-width:24px}
#tp-list li .t{flex:1;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
#tp-list li .like{background:none;border:0;cursor:pointer;font-size:14px;color:#888;padding:0 2px}
#tp-list li .like:hover{color:#f55}
#tp-list li .like.liked{color:#f33;cursor:default}
#tp-list li .like:disabled{opacity:.3;cursor:not-allowed}
`;
document.head.appendChild(css);
// ---------- UI ----------
const btn = document.createElement('button');
btn.id = 'tp-btn';
btn.textContent = '▶ Play all';
document.body.appendChild(btn);
const panel = document.createElement('div');
panel.id = 'tp-panel';
panel.innerHTML = `
<div id="tp-head"><b>Thread playlist</b><button id="tp-close">✕</button></div>
<iframe id="tp-player" referrerpolicy="strict-origin-when-cross-origin" allow="autoplay; encrypted-media; picture-in-picture" allowfullscreen></iframe>
<div id="tp-ctrl">
<button id="tp-prev" title="Previous">⏮</button>
<button id="tp-next" title="Next">⏭</button>
<button id="tp-shuf" title="Shuffle">🔀</button>
<button id="tp-follow" class="on" title="Scroll to the current song's post">📍</button>
<button id="tp-rescan" title="Rescan page">⟳</button>
<span id="tp-now"></span>
</div>
<ul id="tp-list"></ul>`;
document.body.appendChild(panel);
const $ = s => panel.querySelector(s);
const player = $('#tp-player');
player.referrerPolicy = 'strict-origin-when-cross-origin';
function renderList() {
const ul = $('#tp-list');
const frag = document.createDocumentFragment();
playlist.forEach((it, i) => {
const li = document.createElement('li');
li.dataset.i = i;
li.className = (i === index ? 'cur ' : '') + (isDead(it) ? 'dead' : '');
li.innerHTML = `<span class="n">${i + 1}</span><span class="t"></span><button class="like"></button>`;
li.querySelector('.t').textContent = it.label;
const lb = li.querySelector('.like');
const hasBtn = !!likeLink(it);
const liked = isLiked(it);
lb.textContent = liked ? '♥' : '♡';
lb.classList.toggle('liked', liked);
lb.disabled = !hasBtn;
lb.title = !hasBtn ? 'No Like button (logged out?)' : liked ? 'Already liked' : 'Like this post';
frag.appendChild(li);
});
ul.replaceChildren(frag);
}
let renderQueued = false;
function scheduleRender() {
if (renderQueued) return;
renderQueued = true;
setTimeout(() => { renderQueued = false; renderList(); }, 150);
}
$('#tp-list').addEventListener('click', e => {
const li = e.target.closest('li');
if (!li) return;
const it = playlist[+li.dataset.i];
if (!it) return;
if (e.target.closest('.like')) like(it);
else play(+li.dataset.i);
});
// scrolls to the post itself, never to the embed
function scrollToPost(it) {
if (!follow || !it.article?.isConnected) return;
it.article.scrollIntoView({ behavior: 'auto', block: 'start' });
}
// ---------- player control (postMessage, no external script) ----------
function send(func, args = []) {
player.contentWindow?.postMessage(JSON.stringify({ event: 'command', func, args }), '*');
}
function listen() {
const w = player.contentWindow;
if (!w) return;
w.postMessage(JSON.stringify({ event: 'listening', id: 1, channel: 'widget' }), '*');
w.postMessage(JSON.stringify({ event: 'command', func: 'addEventListener', args: ['onStateChange'], id: 1, channel: 'widget' }), '*');
}
// retry the handshake until the player answers
let gotMsg = false, listenTimer = 0;
function startListening() {
clearInterval(listenTimer);
gotMsg = false;
let n = 0;
listenTimer = setInterval(() => {
if (gotMsg || ++n > 40) return clearInterval(listenTimer); // up to ~20s
listen();
}, 500);
}
player.addEventListener('load', () => {
if (player.src === 'about:blank') return;
ready = true;
startListening();
});
function play(i) {
if (!playlist.length) return;
index = ((i % playlist.length) + playlist.length) % playlist.length;
const it = playlist[index];
lastPlay = Date.now();
$('#tp-now').textContent = it.label;
document.title = '▶ ' + it.label;
if (!ready) {
player.src = `https://www.youtube-nocookie.com/embed/${it.id}?enablejsapi=1&autoplay=1&origin=${encodeURIComponent(location.origin)}`;
} else {
send('loadVideoById', [it.id]);
}
renderList();
panel.querySelector('li.cur')?.scrollIntoView({ block: 'nearest' });
scrollToPost(it);
}
function pickNext() {
const n = playlist.length;
if (!n) return -1;
if (shuffle && n > 1) {
for (let tries = 0; tries < 20; tries++) {
const r = Math.floor(Math.random() * n);
if (r !== index && !isDead(playlist[r])) return r;
}
}
for (let k = 1; k <= n; k++) {
const j = (index + k) % n;
if (!isDead(playlist[j])) return j;
}
return -1;
}
function next() {
const j = pickNext();
if (j >= 0) play(j);
}
let lastEnd = 0;
function onEnded() {
const now = Date.now();
if (now - lastEnd < 1500) return; // debounce duplicate end events
if (now - lastPlay < 2000) return; // ignore stale "ended" right after switching tracks
lastEnd = now;
next();
}
window.addEventListener('message', e => {
// filter by origin rather than e.source, which can fail inside the userscript sandbox
if (!/^https:\/\/(www\.)?youtube(-nocookie)?\.com$/.test(e.origin)) return;
let d = e.data;
if (typeof d === 'string') { try { d = JSON.parse(d); } catch { return; } }
if (!d || typeof d !== 'object') return;
gotMsg = true;
if (d.event === 'onStateChange') {
if (d.info === 1) errorStreak = 0;
if (d.info === 0) onEnded();
} else if (d.event === 'onError') {
console.warn('[tp] skipping, error', d.info);
if (++errorStreak <= playlist.length) next();
} else if (d.event === 'infoDelivery' && d.info) {
// fallback: state also arrives bundled in infoDelivery
if (d.info.playerState === 1) errorStreak = 0;
if (d.info.playerState === 0) onEnded();
const vd = d.info.videoData;
const cur = playlist[index];
if (vd?.title && cur && vd.video_id === cur.id && !titleCache[cur.id]?.title) {
titleCache[cur.id] = { title: vd.title, author: vd.author };
saveCache();
cur.label = cleanTitle(vd.title);
$('#tp-now').textContent = cur.label;
scheduleRender();
}
}
});
// ---------- wiring ----------
btn.addEventListener('click', () => {
playlist = scrape();
if (!playlist.length) { btn.textContent = '▶ No videos found'; return; }
btn.style.display = 'none';
panel.classList.add('open');
ready = false;
errorStreak = 0;
play(0);
resolveTitles(playlist);
});
$('#tp-close').addEventListener('click', () => {
clearInterval(listenTimer);
panel.classList.remove('open');
btn.style.display = '';
btn.textContent = '▶ Play all';
player.src = 'about:blank';
ready = false;
});
$('#tp-next').addEventListener('click', next);
$('#tp-prev').addEventListener('click', () => play(index - 1));
$('#tp-shuf').addEventListener('click', e => {
shuffle = !shuffle;
e.currentTarget.classList.toggle('on', shuffle);
});
$('#tp-follow').addEventListener('click', e => {
follow = !follow;
e.currentTarget.classList.toggle('on', follow);
if (follow && playlist[index]) scrollToPost(playlist[index]);
});
$('#tp-rescan').addEventListener('click', () => {
const curId = playlist[index]?.id;
playlist = scrape();
index = Math.max(0, playlist.findIndex(p => p.id === curId));
renderList();
resolveTitles(playlist);
});
})();
That is definitely in the same realm. Now you could convert it into a Userscript so that it can become an always there button on the page rather than needing to dig that code up and dump it into the console whenever you'd like to export a chat.Cross posting my post here because I think it's relevant? If it's baby's first computer job and I'm a simpleton meatball then just give me some trashcans and I'll delete the post, if not then I hope it's cool and can help someone else.