r/Littux • • 5d ago

New bookmarklet See "Top Members" leaderboard on desktop and mobile browsers (without the Android Reddit app)

Post image
8 Upvotes

I made a bookmarklet for it:

javascript:(async()=>{try{await (async()=>{"use strict";const pingURL=url=>{return new Promise(resolve=>{const img=new Image;img.onload=()=>resolve();img.onerror=()=>resolve();img.src=url%2B(url.includes("?")?"&":"?")%2B"v="%2BDate.now()})};const getCookie=async name=>{if(typeof window.cookieStore?.get==="function"){return(await cookieStore.get(name))?.value??null}const cookie="; "%2Bdocument.cookie%2B";";const searchPattern="; "%2Bname%2B"=";const patternStartIndex=cookie.indexOf(searchPattern);if(patternStartIndex===-1)return null;const valueStartIndex=patternStartIndex%2BsearchPattern.length;return decodeURIComponent(cookie.substring(valueStartIndex,cookie.indexOf(";",valueStartIndex)))};const getCookiePing=async(name,pingSrc)=>{let cookieData=await getCookie(name);if(!cookieData){await pingURL(pingSrc);cookieData=await getCookie(name);if(!cookieData)throw new Error("Failed getting cookie '"%2Bname%2B"' by fetching "%2BpingSrc)}return cookieData};const loid=(await getCookie("loid"))?.split(".",1)?.[0];if(!loid&&location.hostname!=="localhost"){alert("Error getting loid");return}const TOKEN_KEY=`rAPI:accessToken~${loid}`;const EXPIRY_KEY=`rAPI:accessTokenExpiry~${loid}`;const getToken=async()=>{if(window?.___r?.session?.accessToken&&window.___r.session?.expires>Date.now())return window.___r.session.accessToken;let token=localStorage.getItem(TOKEN_KEY);let expiry=Number(localStorage.getItem(EXPIRY_KEY));if(token&&expiry>Date.now()){console.log("Using previously cached access token from localStorage");return token}else{token=expiry=null;localStorage.removeItem(TOKEN_KEY);localStorage.removeItem(EXPIRY_KEY);console.debug("No valid access token in localStorage. Deleted cached token.")}if(location.host==="www.reddit.com"||location.host==="sh.reddit.com"){let csrf_token=await getCookiePing("csrf_token","https://sh.reddit.com/404");await fetch("/svc/shreddit/token",{headers:{"Content-Type":"application/json"},method:"POST",body:`{"csrf_token":"${csrf_token}"}`}).then(resp=>resp.text()).then(text=>{const data=JSON.parse(text);console.debug("Got data from /svc/shreddit/token, token expires at "%2Bnew Date(data.expires).toString());token=data.token,expiry=data.expires})}if(!token){throw new Error("error getting access token with /svc/shreddit/token")}localStorage.setItem(TOKEN_KEY,token);localStorage.setItem(EXPIRY_KEY,expiry.toString());return token};window.gqlFetch??=async function gqlFetch(operationName,hash,variables){const response=await fetch("https://gql-fed.reddit.com/?"%2BoperationName,{headers:{"Content-Type":"application/json",Authorization:"Bearer "%2Bawait getToken(),Accept:"application/json"},method:"POST",body:JSON.stringify({operationName:operationName,variables:variables,extensions:{persistedQuery:{version:1,sha256Hash:hash}}})});if(!response.ok){throw new Error(`GraphQL request failed: ${response.status} ${response.statusText}`)}const result=await response.json();if(result.errors?.length){throw new Error(result.errors.map(error=>error.message||"Unknown GraphQL error").join("; "))}if(!result.data){throw new Error("GraphQL response did not contain data")}return result.data};const HOST_ID="clb-leaderboard-modal-host";const DEFAULT_AVATAR_URL="/static/shreddit/assets/snoovatar-back-64x64px.png";function safeUrl(url){if(typeof url!=="string")return"";try{const parsed=new URL(url,window.location.origin);if(parsed.protocol==="https:"||parsed.protocol==="http:"){return parsed.href}}catch{return""}return""}function detectSubredditFromUrl(){const match=window.location.pathname.match(/^/r/([^/]%2B)/i);return match?decodeURIComponent(match[1]):""}function el(tag,className,text){const node=document.createElement(tag);if(className)node.className=className;if(text!==undefined&&text!==null)node.textContent=String(text);return node}const STYLES=`%0A:host {%0A%09all: initial;%0A%09font-family: RedditSans, 'Reddit Sans', IBMPlexSans, Arial, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;%0A%09color-scheme: var(--clb-color-scheme);%0A%09--clb-color-scheme: dark;%0A%09--clb-surface: %230e1113;%0A%09--clb-text: %23eef1f3;%0A%09--clb-text-strong: %23ffffff;%0A%09--clb-text-secondary: %238ba2ad;%0A%09--clb-text-muted: %237b8f99;%0A%09--clb-border: %23242c31;%0A%09--clb-border-subtle: %2322292e;%0A%09--clb-control-bg: %231a2126;%0A%09--clb-control-text: %23b8c4ca;%0A%09--clb-control-hover: %23273138;%0A%09--clb-tab-border: %232a3339;%0A%09--clb-tab-bg: %23151b1f;%0A%09--clb-tab-hover: %231d252a;%0A%09--clb-tab-active: %23253038;%0A%09--clb-tab-active-border: %23465763;%0A%09--clb-divider: %23181f24;%0A%09--clb-divider-border: %23232b30;%0A%09--clb-row-hover: %23151b1f;%0A%09--clb-row-current: %2317232b;%0A%09--clb-scrollbar-thumb: %232a3339;%0A%09--clb-avatar-bg: %231d252a;%0A%09--clb-link: %236a9bff;%0A%09--clb-score-change: %2300c29d;%0A%09--clb-error: %23ff6b6b;%0A%09--clb-button-border: %232b353c;%0A%09--clb-button-hover: %23232d34;%0A%09--clb-shadow: rgba(0, 0, 0, 0.65);%0A}%0A%0A@media (prefers-color-scheme: light) {%0A%09:host {%0A%09%09color-scheme: light;%0A%09%09--clb-color-scheme: light;%0A%09%09--clb-surface: %23ffffff;%0A%09%09--clb-text: %231a1a1b;%0A%09%09--clb-text-strong: %231a1a1b;%0A%09%09--clb-text-secondary: %23576f76;%0A%09%09--clb-text-muted: %236b7280;%0A%09%09--clb-border: %23d7dadc;%0A%09%09--clb-border-subtle: %23edeff1;%0A%09%09--clb-control-bg: %23f6f7f8;%0A%09%09--clb-control-text: %23576f76;%0A%09%09--clb-control-hover: %23e9ebed;%0A%09%09--clb-tab-border: %23d7dadc;%0A%09%09--clb-tab-bg: %23f6f7f8;%0A%09%09--clb-tab-hover: %23e9ebed;%0A%09%09--clb-tab-active: %23e3f0ff;%0A%09%09--clb-tab-active-border: %238bb9e8;%0A%09%09--clb-divider: %23f6f7f8;%0A%09%09--clb-divider-border: %23edeff1;%0A%09%09--clb-row-hover: %23f6f7f8;%0A%09%09--clb-row-current: %23eaf3f8;%0A%09%09--clb-scrollbar-thumb: %23d7dadc;%0A%09%09--clb-avatar-bg: %23f0f2f3;%0A%09%09--clb-link: %232463eb;%0A%09%09--clb-score-change: %2300856f;%0A%09%09--clb-error: %23d93025;%0A%09%09--clb-button-border: %23d7dadc;%0A%09%09--clb-button-hover: %23e9ebed;%0A%09%09--clb-shadow: rgba(0, 0, 0, 0.2);%0A%09}%0A}%0A%0A* {%0A%09box-sizing: border-box;%0A}%0A%0A.clb-backdrop {%0A%09position: fixed;%0A%09inset: 0;%0A%09z-index: 2147483647;%0A%09background: rgba(0, 0, 0, 0.72);%0A%09display: flex;%0A%09align-items: center;%0A%09justify-content: center;%0A%09padding: 16px;%0A%09backdrop-filter: blur(2px);%0A}%0A%0A.clb-modal {%0A%09width: 480px;%0A%09height: 100%25;%0A%09max-height: 1080px;%0A%09background: var(--clb-surface);%0A%09color: var(--clb-text);%0A%09border: 1px solid var(--clb-border);%0A%09border-radius: 16px;%0A%09box-shadow: 0 20px 60px var(--clb-shadow);%0A%09display: flex;%0A%09flex-direction: column;%0A%09overflow: hidden;%0A}%0A%0A.clb-header {%0A%09padding: 18px 20px 14px;%0A%09background: var(--clb-surface);%0A%09border-bottom: 1px solid var(--clb-border-subtle);%0A%09position: relative;%0A}%0A%0A.clb-header-top {%0A%09display: flex;%0A%09align-items: flex-start;%0A%09justify-content: space-between;%0A%09gap: 12px;%0A}%0A%0A.clb-title {%0A%09margin: 0;%0A%09font-size: 22px;%0A%09font-weight: 700;%0A%09line-height: 1.25;%0A%09color: var(--clb-text-strong);%0A%09letter-spacing: -0.01em;%0A}%0A%0A.clb-close-btn {%0A%09appearance: none;%0A%09border: none;%0A%09background: var(--clb-control-bg);%0A%09color: var(--clb-control-text);%0A%09width: 32px;%0A%09height: 32px;%0A%09border-radius: 999px;%0A%09font-size: 20px;%0A%09line-height: 1;%0A%09cursor: pointer;%0A%09display: inline-flex;%0A%09align-items: center;%0A%09justify-content: center;%0A%09flex-shrink: 0;%0A%09transition: background 0.15s ease, color 0.15s ease;%0A}%0A%0A.clb-close-btn:hover {%0A%09background: var(--clb-control-hover);%0A%09color: var(--clb-text-strong);%0A}%0A%0A.clb-subtitle {%0A%09margin: 6px 0 0;%0A%09font-size: 14px;%0A%09line-height: 1.4;%0A%09color: var(--clb-text-secondary);%0A}%0A%0A.clb-learn-more {%0A%09color: var(--clb-link);%0A%09text-decoration: none;%0A%09font-weight: 500;%0A}%0A%0A.clb-learn-more:hover {%0A%09text-decoration: underline;%0A}%0A%0A.clb-tabs {%0A%09display: flex;%0A%09gap: 8px;%0A%09margin-top: 14px;%0A%09flex-wrap: wrap;%0A}%0A%0A.clb-tab {%0A%09appearance: none;%0A%09border: 1px solid var(--clb-tab-border);%0A%09background: var(--clb-tab-bg);%0A%09color: var(--clb-control-text);%0A%09font-size: 13px;%0A%09font-weight: 600;%0A%09padding: 6px 12px;%0A%09border-radius: 999px;%0A%09cursor: pointer;%0A%09transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;%0A}%0A%0A.clb-tab:hover {%0A%09background: var(--clb-tab-hover);%0A%09color: var(--clb-text-strong);%0A}%0A%0A.clb-tab.is-active {%0A%09background: var(--clb-tab-active);%0A%09color: var(--clb-text-strong);%0A%09border-color: var(--clb-tab-active-border);%0A}%0A%0A.clb-body {%0A%09overflow-y: auto;%0A%09flex: 1 1 auto;%0A%09background: var(--clb-surface);%0A}%0A%0A.clb-body::-webkit-scrollbar {%0A%09width: 8px;%0A}%0A%0A.clb-body::-webkit-scrollbar-track {%0A%09background: var(--clb-surface);%0A}%0A%0A.clb-body::-webkit-scrollbar-thumb {%0A%09background: var(--clb-scrollbar-thumb);%0A%09border-radius: 4px;%0A}%0A%0A.clb-delimiter {%0A%09display: flex;%0A%09align-items: center;%0A%09justify-content: space-between;%0A%09padding: 10px 18px;%0A%09background: var(--clb-divider);%0A%09border-top: 1px solid var(--clb-divider-border);%0A%09border-bottom: 1px solid var(--clb-divider-border);%0A%09position: sticky;%0A%09top: 0;%0A%09z-index: 2;%0A}%0A%0A.clb-delimiter-left {%0A%09display: flex;%0A%09align-items: center;%0A%09gap: 8px;%0A%09min-width: 0;%0A}%0A%0A.clb-delimiter-icon {%0A%09width: 20px;%0A%09height: 20px;%0A%09object-fit: contain;%0A%09flex-shrink: 0;%0A}%0A%0A.clb-delimiter-title {%0A%09font-size: 15px;%0A%09font-weight: 700;%0A%09color: var(--clb-text-strong);%0A%09white-space: nowrap;%0A%09overflow: hidden;%0A%09text-overflow: ellipsis;%0A}%0A%0A.clb-delimiter-score {%0A%09font-size: 15px;%0A%09font-weight: 700;%0A%09color: var(--clb-text-strong);%0A%09flex-shrink: 0;%0A}%0A%0A.clb-row {%0A%09display: flex;%0A%09align-items: center;%0A%09justify-content: space-between;%0A%09padding: 9px 18px;%0A%09gap: 12px;%0A%09transition: background 0.12s ease;%0A}%0A%0A.clb-row:hover {%0A%09background: var(--clb-row-hover);%0A}%0A%0A.clb-row.is-current-user {%0A%09background: var(--clb-row-current);%0A%09margin-bottom: 9px;%0A%09border-radius: 8px;%0A}%0A%0A.clb-row-left {%0A%09display: flex;%0A%09align-items: center;%0A%09gap: 12px;%0A%09min-width: 0;%0A%09flex: 1 1 auto;%0A}%0A%0A.clb-rank {%0A%09width: 24px;%0A%09text-align: center;%0A%09font-size: 15px;%0A%09font-weight: 700;%0A%09color: var(--clb-text-strong);%0A%09font-variant-numeric: tabular-nums;%0A%09flex-shrink: 0;%0A}%0A%0A.clb-avatar-wrap {%0A%09position: relative;%0A%09width: 34px;%0A%09height: 34px;%0A%09flex-shrink: 0;%0A}%0A%0A.clb-avatar {%0A%09width: 34px;%0A%09height: 34px;%0A%09border-radius: 999px;%0A%09object-fit: cover;%0A%09background: var(--clb-avatar-bg);%0A%09display: block;%0A}%0A%0A.clb-pos-icon {%0A%09position: absolute;%0A%09right: -3px;%0A%09bottom: -3px;%0A%09width: 14px;%0A%09height: 14px;%0A%09object-fit: contain;%0A}%0A%0A.clb-username {%0A%09height: 18px;%0A%09font-size: 16px;%0A%09font-weight: bold;%0A%09color: var(--clb-text);%0A%09text-decoration: none;%0A%09white-space: nowrap;%0A%09overflow: hidden;%0A%09text-overflow: ellipsis;%0A}%0A%0Aa.clb-username:hover {%0A%09text-decoration: underline;%0A%09color: var(--clb-text-strong);%0A}%0A%0A.clb-username.is-deleted {%0A%09color: var(--clb-text-muted);%0A}%0A%0A.clb-row-right {%0A%09display: flex;%0A%09align-items: baseline;%0A%09gap: 6px;%0A%09flex-shrink: 0;%0A%09font-variant-numeric: tabular-nums;%0A}%0A%0A.clb-score-change {%0A%09font-size: 14px;%0A%09font-weight: 600;%0A%09color: var(--clb-score-change);%0A}%0A%0A.clb-score {%0A%09font-size: 15px;%0A%09font-weight: 500;%0A%09color: var(--clb-text);%0A}%0A%0A.clb-status {%0A%09padding: 28px 20px;%0A%09text-align: center;%0A%09font-size: 14px;%0A%09color: var(--clb-text-secondary);%0A}%0A%0A.clb-status.is-error {%0A%09color: var(--clb-error);%0A}%0A%0A.clb-load-more-wrap {%0A%09padding: 12px 18px 16px;%0A%09display: flex;%0A%09justify-content: center;%0A}%0A%0A.clb-load-more-btn {%0A%09appearance: none;%0A%09border: 1px solid var(--clb-button-border);%0A%09background: var(--clb-divider);%0A%09color: var(--clb-text);%0A%09font-size: 13px;%0A%09font-weight: 600;%0A%09padding: 8px 18px;%0A%09border-radius: 999px;%0A%09cursor: pointer;%0A%09transition: background 0.15s ease;%0A}%0A%0A.clb-load-more-btn:hover:not(:disabled) {%0A%09background: var(--clb-button-hover);%0A}%0A%0A.clb-load-more-btn:disabled {%0A%09opacity: 0.6;%0A%09cursor: default;%0A}%0A%0A.clb-footer {%0A%09padding: 10px 18px 14px;%0A%09border-top: 1px solid var(--clb-border-subtle);%0A%09background: var(--clb-surface);%0A%09font-size: 12px;%0A%09line-height: 1.45;%0A%09color: var(--clb-text-muted);%0A%09display: flex;%0A%09flex-direction: column;%0A%09gap: 2px;%0A}`;function buildDelimiterRow(node){const row=el("div","clb-delimiter");const left=el("div","clb-delimiter-left");const iconUrl=safeUrl(node.icon?.url);if(iconUrl){const img=el("img","clb-delimiter-icon");img.src=iconUrl;img.alt="";img.loading="lazy";left.appendChild(img)}left.appendChild(el("span","clb-delimiter-title",node.title||""));row.appendChild(left);row.appendChild(el("span","clb-delimiter-score",node.scoreLabel||""));return row}function buildUserRow(node,isCurrentUser=false){const row=el("div",isCurrentUser?"clb-row is-current-user":"clb-row");const left=el("div","clb-row-left");left.appendChild(el("span","clb-rank",node.rankLabel??""));const avatarWrap=el("div","clb-avatar-wrap");const avatar=el("img","clb-avatar");let displayName="[deleted]";let profileHref="";let avatarUrl="";let isDeleted=false;if(node.user&&node.user.__typename==="Redditor"){displayName=node.user.prefixedName||(node.user.name?`u/${node.user.name}`:"[deleted]");avatarUrl=safeUrl(node.user.icon?.url||node.user.snoovatarIcon?.url);if(node.user.name){profileHref=`https://www.reddit.com/user/${encodeURIComponent(node.user.name)}`}}else if(node.maskedUser){displayName=node.maskedUser.name||"Hidden Redditor";avatarUrl=safeUrl(node.maskedUser.icon?.url)}else{isDeleted=true}avatar.src=avatarUrl||DEFAULT_AVATAR_URL;avatar.alt=displayName;avatar.loading="lazy";avatar.onerror=()=>{if(avatar.src!==DEFAULT_AVATAR_URL)avatar.src=DEFAULT_AVATAR_URL};avatarWrap.appendChild(avatar);const posIconUrl=safeUrl(node.positionChangeIcon?.url||node.rankIcon?.url);if(posIconUrl){const posIcon=el("img","clb-pos-icon");posIcon.src=posIconUrl;posIcon.alt="";avatarWrap.appendChild(posIcon)}left.appendChild(avatarWrap);if(profileHref){const link=el("a","clb-username",displayName);link.href=profileHref;link.target="_blank";link.rel="noopener noreferrer";left.appendChild(link)}else{left.appendChild(el("span",isDeleted?"clb-username is-deleted":"clb-username",displayName))}row.appendChild(left);const right=el("div","clb-row-right");if(node.scoreInfo?.scoreChangeLabel){const change=el("span","clb-score-change",node.scoreInfo.scoreChangeLabel);if(node.scoreInfo.textColor){change.style.color=node.scoreInfo.textColor}right.appendChild(change)}right.appendChild(el("span","clb-score",node.currentScoreLabel??""));row.appendChild(right);return row}async function openCommunityLeaderboardModal(subredditName,initialCategoryId=null){const existing=document.getElementById(HOST_ID);if(existing)existing.remove();const targetSubreddit=subredditName&&String(subredditName).trim()||detectSubredditFromUrl()||window.prompt("Enter subreddit name (without r/):","spezholedesign")?.trim();if(!targetSubreddit)return;const host=document.createElement("div");host.id=HOST_ID;const shadow=host.attachShadow({mode:"open"});const style=document.createElement("style");style.textContent=STYLES;shadow.appendChild(style);const backdrop=el("div","clb-backdrop");const modal=el("div","clb-modal");modal.setAttribute("role","dialog");modal.setAttribute("aria-modal","true");const header=el("div","clb-header");const headerTop=el("div","clb-header-top");const titleEl=el("h2","clb-title",`r/${targetSubreddit}`);const closeBtn=el("button","clb-close-btn","×");closeBtn.type="button";closeBtn.setAttribute("aria-label","Close modal");headerTop.appendChild(titleEl);headerTop.appendChild(closeBtn);header.appendChild(headerTop);const subtitleEl=el("p","clb-subtitle");header.appendChild(subtitleEl);const tabsEl=el("div","clb-tabs");header.appendChild(tabsEl);const body=el("div","clb-body");const footer=el("div","clb-footer");footer.hidden=true;modal.appendChild(header);modal.appendChild(body);modal.appendChild(footer);backdrop.appendChild(modal);shadow.appendChild(backdrop);document.body.appendChild(host);let activeCategoryId=initialCategoryId;let endCursor="";let hasNextPage=false;let isLoading=false;let requestToken=0;function closeModal(){document.removeEventListener("keydown",onKeyDown);host.remove()}function onKeyDown(e){if(e.key==="Escape")closeModal()}closeBtn.addEventListener("click",closeModal);backdrop.addEventListener("click",e=>{if(e.target===backdrop)closeModal()});document.addEventListener("keydown",onKeyDown);function renderEdges(edges){const fragment=document.createDocumentFragment();for(const edge of edges||[]){const node=edge?.node;if(!node)continue;if(node.__typename==="RankingDelimiter"){fragment.appendChild(buildDelimiterRow(node))}else if(node.__typename==="CommunityLeaderboardUser"){fragment.appendChild(buildUserRow(node))}}return fragment}function updateLoadMoreControl(){const prevWrap=body.querySelector(".clb-load-more-wrap");if(prevWrap)prevWrap.remove();if(!hasNextPage)return;const wrap=el("div","clb-load-more-wrap");const btn=el("button","clb-load-more-btn",isLoading?"Loading…":"Load more");btn.type="button";btn.disabled=isLoading;btn.addEventListener("click",()=>loadNextPage());wrap.appendChild(btn);body.appendChild(wrap)}function renderHeaderAndFooter(categories,currentCat){const activePeriod=currentCat?.periodList?.find(p=>p.isActive)||currentCat?.periodList?.[0];titleEl.textContent=activePeriod?.name||currentCat?.name||`r/${targetSubreddit}`;subtitleEl.textContent="";if(currentCat?.description){subtitleEl.appendChild(document.createTextNode(`${currentCat.description} `))}const learnUrl=safeUrl(currentCat?.deeplinkUrl);if(learnUrl){const a=el("a","clb-learn-more","Learn more");a.href=learnUrl;a.target="_blank";a.rel="noopener noreferrer";subtitleEl.appendChild(a)}tabsEl.textContent="";if(Array.isArray(categories)&&categories.length>1){tabsEl.hidden=false;for(const cat of categories){const btn=el("button",cat.id===activeCategoryId?"clb-tab is-active":"clb-tab",cat.name);btn.type="button";btn.addEventListener("click",()=>{if(cat.id!==activeCategoryId){loadLeaderboard(cat.id)}});tabsEl.appendChild(btn)}}else{tabsEl.hidden=true}const metaParts=[currentCat?.updateIntervalLabel,currentCat?.lastUpdatedLabel].filter(Boolean);if(metaParts.length>0){footer.appendChild(el("div","",metaParts.join(" • ")))}if(currentCat?.footerText){footer.appendChild(el("div","",currentCat.footerText))}footer.hidden=footer.childElementCount===0}async function loadLeaderboard(categoryId){const token=%2B%2BrequestToken;isLoading=true;hasNextPage=false;endCursor="";body.textContent="";body.appendChild(el("div","clb-status","Loading leaderboard…"));try{const variables={subredditName:targetSubreddit};if(categoryId)variables.categoryId=categoryId;const data=await window.gqlFetch("CommunityLeaderboard","2453122c624fc5675ee3fc21f59372a6ae9ef63be3cb4f3072038b162bf21280",variables);if(token!==requestToken)return;const lb=data?.subredditInfoByName?.communityLeaderboard;if(!lb){body.textContent="";body.appendChild(el("div","clb-status",`No community leaderboard found for r/${targetSubreddit}.`));return}const categories=lb.categories||[];const currentCat=categories.find(c=>c.id===categoryId)||categories.find(c=>c.isActive)||categories[0]||null;activeCategoryId=currentCat?.id||categoryId||null;body.textContent="";footer.textContent="";const ranking=lb.ranking;if(ranking?.currentUserRank){footer.appendChild(buildUserRow(ranking.currentUserRank,true))}renderHeaderAndFooter(categories,currentCat);const edges=ranking?.edges||[];if(edges.length===0){body.appendChild(el("div","clb-status","No rankings available yet."))}else{body.appendChild(renderEdges(edges))}endCursor=ranking?.pageInfo?.endCursor||"";hasNextPage=Boolean(ranking?.pageInfo?.hasNextPage&&endCursor);updateLoadMoreControl()}catch(err){if(token!==requestToken)return;body.textContent="";body.appendChild(el("div","clb-status is-error",`Failed to load leaderboard: ${err?.message||err}`))}finally{if(token===requestToken){isLoading=false;updateLoadMoreControl()}}}async function loadNextPage(){if(isLoading||!hasNextPage||!endCursor)return;const token=requestToken;isLoading=true;updateLoadMoreControl();try{const variables={subredditName:targetSubreddit,after:endCursor};if(activeCategoryId)variables.categoryId=activeCategoryId;const data=await window.gqlFetch("CommunityLeaderboardPage","ef6d0a4d10971569834a07c01c3c4afa408ef22f4c062a9e8d7d45da4c800a81",variables);if(token!==requestToken)return;const ranking=data?.subredditInfoByName?.communityLeaderboard?.ranking;const wrap=body.querySelector(".clb-load-more-wrap");if(wrap)wrap.remove();body.appendChild(renderEdges(ranking?.edges||[]));endCursor=ranking?.pageInfo?.endCursor||"";hasNextPage=Boolean(ranking?.pageInfo?.hasNextPage&&endCursor)}catch(err){if(token!==requestToken)return;body.appendChild(el("div","clb-status is-error",`Failed to load more: ${err?.message||err}`))}finally{if(token===requestToken){isLoading=false;updateLoadMoreControl()}}}body.addEventListener("scroll",()=>{if(!hasNextPage||isLoading)return;if(body.scrollTop%2Bbody.clientHeight>=body.scrollHeight-120){loadNextPage()}});await loadLeaderboard(initialCategoryId)}window.openCommunityLeaderboardModal=openCommunityLeaderboardModal;await openCommunityLeaderboardModal()})();}catch(e){console.error("Bookmarklet failed:", e.message);alert("Bookmarklet failed: " %2B e.message)}})();

On a desktop browser, you can right click on the top bar and add a bookmark. Call it something like "Subreddit Leaderboard". Paste the code above as the URL. Now, go to the subreddit where you want to view the leaderboard. Then click on the bookmark to run it.

On a mobile browser, go to any page and bookmark it with the star button. Then go to all bookmarks and find the newly created bookmark. Edit it and change the title to your liking and enter the code as URL. Now, open the subreddit page of your choosing, and click on the address bar. Enter whatever you entered as the title of the bookmark on the address bar. On the bottom of the search suggestions, you should see the bookmark. Just tap on it to run it

Edit: added light mode support


r/Littux • • 12d ago

New reddit/d2x update new.reddit.com recovery release v0.9.0: now with keyword filtering of posts

Thumbnail
github.com
4 Upvotes

The client now supports keyword filtering of posts. After updating, check out http://localhost:1264/config.html#filters. There are two options there: "Fully hide filtered posts" and "Show a toast when posts are filtered". Enable "Fully hide filtered posts" if you don't want to see "Post hidden (Unhide)" cards, and disable "Show a toast when posts are filtered" if you don't want to see "Filtered x posts by post filter 'Filter name'" messages

Screenshot with 'Fully hide filtered posts' disabled and 'Show a toast when posts are filtered' enabled

You can import JSON filters using the "Import" button next to "Subreddit filters" and "Post filters" in the filters menu. This makes it possible to share filters with people, and ask AI to make filters for you. You can use this Gemini skill to ask Gemini to make filters for you: https://gemini.google.com/customize/skills/d/16dCj4CILzA5CJ6DIlDynYTvNjMJqLKlZ

Gemini screenshot

Changes

Fixes

GQL

  • Videos not playing due to CORS if cf.v.redd.it experiment active ("Video no longer available" or endless buffering)
  • Deleted posts causing errors on post comments
  • Comments removed by reddit having "Admin" label
  • Empty captions on gallery posts
  • All posts appearing as if they have an unknown suggested sort
  • removedByCategory being ignored due to being uppercase (removed posts no longer always show "Removed by spam filter")
  • Fix "continue this thread" under a deleted comment not working
  • Fix poll posts
  • Fix devvit posts

Others

  • Restore hide post button

Improvements

  • Add "Top 1% Poster" etc labels as user flair in post comments
  • Add config options: disable auto collapsing of comments (gql), ability to force a post image quality (gql)
  • See log messages during client startup
  • Always enable gql request deduplication
  • r/popular feed geo_filter (the API is bugged so may not work)

r/Littux • • 12d ago

Messed up the release again

Thumbnail
github.com
3 Upvotes

Messed up the previous release (didn't update the version in the code and didn't push a commit with some fixes). Here's the changelog of the previous release: https://www.reddit.com/r/Littux/comments/1y2pljn/newredditcom_recovery_release_v090_now_with/


r/Littux • • 20d ago

New bookmarklet I made a bookmarklet to migrate an old reddit wiki page to the new wiki

5 Upvotes

It can transfer the current wiki page you have opened from old to new, but not the opposite. Most formatting will work, including images. The spoiler tag doesn't work. Here's the bookmarklet:

javascript:(async()=>{try{await (async()=>{const pingURL=url=>{return new Promise(resolve=>{const img=new Image;img.onload=()=>resolve();img.onerror=()=>resolve();img.src=url%2B(url.includes("?")?"&":"?")%2B"v="%2BDate.now()})};const getCookie=async name=>{if(typeof window.cookieStore?.get==="function"){return(await cookieStore.get(name))?.value??null}const cookie="; "%2Bdocument.cookie%2B";";const searchPattern="; "%2Bname%2B"=";const patternStartIndex=cookie.indexOf(searchPattern);if(patternStartIndex===-1)return null;const valueStartIndex=patternStartIndex%2BsearchPattern.length;return decodeURIComponent(cookie.substring(valueStartIndex,cookie.indexOf(";",valueStartIndex)))};const getCookiePing=async(name,pingSrc)=>{let cookieData=await getCookie(name);if(!cookieData){await pingURL(pingSrc);cookieData=await getCookie(name);if(!cookieData)throw new Error("Failed getting cookie '"%2Bname%2B"' by fetching "%2BpingSrc)}return cookieData};async function getREST(endpoint){const response=await fetch(endpoint,{method:"GET",headers:{Accept:"application/json"}});if(!response.ok)throw new Error(`Failed to fetch ${endpoint}: ${response.status}`);return await response.json()}async function svcGqlFetch(operation,variables){const csrfToken=await getCookiePing("csrf_token","https://sh.reddit.com/404");const response=await fetch("/svc/shreddit/graphql",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({operation:operation,variables:variables,csrf_token:csrfToken})});if(!response.ok)throw new Error(`GraphQL request failed for ${operation}: ${response.status}`);const responseData=await response.json();if(responseData.errors?.length)throw new Error(`GraphQL request for ${operation} returned errors: ${JSON.stringify(responseData.errors)}`);return responseData.data}const wikiUrlMatch=location.pathname.match(/^/r/([^/]%2B)/wiki/(?:(?:edit|settings)/)?(.%2B)$/);if(!wikiUrlMatch)throw new Error("Not a wiki page URL");const subredditName=wikiUrlMatch[1];const pageName=wikiUrlMatch[2];const wikiPageData=await getREST(`/r/${subredditName}/wiki/${pageName}.json?raw_json=1`);if(!wikiPageData||wikiPageData.kind!=="wikipage")throw new Error("Failed to fetch wiki page data");const{content_html,reason}=wikiPageData.data;const contentDoc=(new DOMParser).parseFromString(content_html,"text/html");contentDoc.querySelectorAll("td, th").forEach(col=>{const align=col.getAttribute("align");if(align){col.style.textAlign=align;col.removeAttribute("align")}});const{upsertWikiPage}=await svcGqlFetch("UpsertWikiPage",{input:{page:pageName,subredditName:subredditName,reason:reason||"Sync wiki page with old reddit",content:{markdown:contentDoc.body.innerHTML},postToCommunity:false,pageTitle:pageName}});if(!upsertWikiPage.ok){if(upsertWikiPage.isRateLimited){throw new Error(`Rate limited. Try again after: ${upsertWikiPage.rateLimitEndsAt}`)}const{errors,fieldErrors}=upsertWikiPage;throw new Error(`Failed to upsert wiki page: ${JSON.stringify({errors:errors,fieldErrors:fieldErrors},null,2)}`)}alert(`SUCCESS: Wiki page '${pageName}' in subreddit '${subredditName}' has been successfully upserted.`)})();}catch(e){console.error("Bookmarklet failed:", e.message);alert("Bookmarklet failed: " %2B e.message)}})();

On a desktop browser, you can right click on the top bar and add a bookmark. Call it something like "Wiki Old => New". Paste the code above as the URL. Now, go to the wiki page you want to transfer. Then click on the bookmark to run it.

On a mobile browser, go to any page and bookmark it with the star button. Then go to all bookmarks and find the newly created bookmark. Edit it and change the title to your liking and enter the code as URL. Now, open the wiki page you want to transfer, and click on the address bar. Enter whatever you entered as the title of the bookmark on the address bar. On the bottom of the search suggestions, you should see the bookmark. Just tap on it to run it


The script is fairly basic. The new wiki uses raw HTML for formatting instead of markdown. The script fetches the wiki page rendered HTML and revision reason from the API, and just creates the new wiki page with the old reddit rendered HTML and the same revision reason. It does some modifications to the old reddit HTML so that table column alignment options work (converts align='left' to style="text-align: left;" etc)


r/Littux • • 28d ago

New reddit/d2x update new.reddit.com client recovery release v0.8.1: The final release you'll have to manually update

Thumbnail github.com
9 Upvotes

You need to download assets.zip and extract it as a folder called "cached" in bundles/, which is inside release.zip (so you need to extract that first)


This release brings an update checker and update installer to the client. Since the previous release v0.8.0 had issues with the updater (as expected), I had to make a new release with some fixes. This is the release note of the previous release:


Bugs/Issues fixed

  • Migrate StoreUxTargetingAction (ability to dismiss the surveys in home feed)
  • GraphQL post feed fixes:

    • Empty captions on galleries
    • Errors due to lack of null checking|
    • null upvotes on AdPost
  • GraphQL moderationInfo mod actions showing up as made at 1970
  • Fix restoring of scroll position (now repeatedly scrolls until reaching target position)

Improvements/Misc

  • New settings:

    • Use GraphQL for comments page
    • Comments max depth (GraphQL)
  • Migrate post comments to GraphQL (awards now appear, loading speed improved, now works logged out)
  • Speed up loading of redd.it links
  • More readable errors if statusText is empty (fixes large toast messages appearing due to network errors)
  • Reuse existing Reddit Sans font instead of loading new
  • Larger images in comments (same height but now uses the horizontal space better)
  • Update checker and installer

How to use?

https://www.reddit.com/r/ReturnNewReddit/comments/1vmgvmt/beautiful_right_now_you_can_enjoy_it_too/

(The tutorial above may be replaced due to the new steps and features added since its creation)


r/Littux • • Nov 03 '26

New reddit/d2x update new.reddit.com client recovery release v0.7.0 (with fix for home feed)

Thumbnail github.com
9 Upvotes

What's changed

To use this version or later version, you need to have a local copy of new.reddit.com assets. Download cachedv1.zip from below. After downloading and extracting release.zip, open the "bundles" folder. Copy and paste the "cachedv1.zip" there. Now extract the zip there (make sure contents are extracted to a subfolder named "cached"). Now you can delete the zip. Now, inside the "bundles" folder, there should be a "cached" folder. Inside of that, there should be lots of .js files and folders.

If you didn't do it correctly, you'll get a white screen.

Bugs/Issues fixed

  • Issue with the homepage has been fixed.
  • Fix comments threadline colour being invisible in light mode
  • Fix reddit premium being ignored
  • Fix search API being blocked (viewing a user's posts)
  • Fix old posts being marked as chat posts

Improvements/Misc

  • New configuration UI (accessible at http://localhost:1264/config.html, access to enable features disabled by default)
  • Load JS bundles from your own storage (UI is now much faster)
  • GraphQL subreddit page (disabled by default)

    • Makes awards show up on posts. However, GIF images on galleries won't play as MP4s (like on the current official site) instead playing as .gif images, which are huge and take long time to load. Though GIFs in galleries are rare and only common on NSFW subreddits
  • Search within a user (buggy: if it doesn't show up in search bar, click back button and go forward after a short delay)
  • Enable experiments:

    • d2x_cdd_active_community_profile (Show "Active in Communities" list on profiles)
    • d2x_inbox_v2_post_embeds (Show preview of posts in notifications)

How to use?

https://www.reddit.com/r/ReturnNewReddit/comments/1vmgvmt/beautiful_right_now_you_can_enjoy_it_too/


r/Littux • • Oct 22 '26

New reddit/d2x update new.reddit.com recovery: Release v0.6.0 (Update NOW if on an older version)

Thumbnail github.com
8 Upvotes

What's changed

Subreddit page and comments page being blocked has been fixed: Reddit has started blocking some API endpoints. Those who have older versions may see "Reddit returned an HTML page (status: 403)" errors. This version will display a proper error, and provide the ability to report the error via a comment

Bugs fixed

  • Fix report form getting stuck loading
  • Fix post body text not appearing on link posts
  • Fix gallery image outbound URL not showing
  • Fix profile info not loading on profile posts
  • Fix redd.it short links not loading on current page
  • Fix gql realtime connection authorization

Improvements

  • Make "SEE FULL IMAGE" button actually work
  • Restore original font
  • Improve custom styling, seperate custom styling to seperate file

    • To remove custom styling, just rename the .css file
  • Fix empty error messages

How to use?

https://www.reddit.com/r/ReturnNewReddit/comments/1vmgvmt/beautiful_right_now_you_can_enjoy_it_too/


r/Littux • • Oct 16 '26

Testing post Thread for reporting "You've been blocked by network security"

Post image
7 Upvotes

Currently, Reddit is blocking some API endpoints. You may see "Reddit returned an HTML page (status: 403)" on the current version. The next release will fix some of them, and will properly display those errors. It will have a feature for reporting such errors via a comment, and those will be sent here


r/Littux • • Sep 23 '26

New reddit/d2x update new.reddit.com recovery release v0.5.0

Thumbnail
github.com
10 Upvotes

What's changed

Contains 7 commits of changes

Bugs fixed

  • Fix crash when allowed_media_in_comments is null
  • Fix submit page crash if subreddit info has already loaded
  • Fix gql subreddit rules fetching
  • Use r2 subreddit for submit page (now the submit page text works again)
  • Better subreddit banned/private etc status
  • Fix bug where arctic-shift was unnecessarily used for current logged-in user
  • Fix cookie domain (now set to the current page's domain instead of .reddit.com)
  • Don't send cookies for gql-realtime POST requests to avoid 403
  • Fix trophy image size by limiting it
  • Fix thumbnails not appearing on posts with body text
  • Fix mistake where fixR2CommentsMedia is run during preload on post comments, slowing down loading
  • Fix deleted comments showing up as "Removed by moderator"
  • Fix no subreddit icons on listing pages by using sr_detail=1 when needed

Improvements

  • Post

    • Improve r2 to gateway post mapping (add dismissed reports, fix obfuscatedUrl)
    • Show post quarantine flair
    • Improve regex used to enable chat mode on posts
    • Better live chat post emulation
  • Comment

    • Fetch moderation info for comments
    • Collapse/expand comment by clicking header
    • Comments page better context
    • Better detection whether if comment is removed by mod
  • Show if posts or comments are removed as spam
  • Always fetch r2 subreddit for subreddit pages and post comments, instead of only using it for profiles (now stuff like post flair position work again)
  • Handle submit page crossposts fetching better (the client fetches it to block you from posting if there is a recent crosspost made less than 24 hours ago on the subreddit)
  • Improve SPA navigation
  • Many styling improvements (reducing padding, increasing pfp size, using Reddit Sans as font etc)
  • Error

    • REST API expect more than 1 status code instead of raising error (no more error toasts when fetching flair if the subreddit doesn't have flair or subreddit doesn't exist)
    • Handle API interceptor errors instead of silently failing
    • Retry API fetch on network errors
    • Improved gql error logging
  • arctic-shift use sort date ascending if "Top" sort used (Top sort isn't supported by arctic-shift)

Misc

  • Migrate gateway user about endpoint
  • Disable treeshake for build
  • Live comments remove UPDATE_COMMENT (leaving only NEW_COMMENT) event
  • localhost API (work in progress)
  • Add reddit_user_id cookie for localhost API
  • Add types for gateway post, flair, media asset, comment and subreddit
  • Refactor subreddit mapping to separate gql mapping to another file
  • Move redux state types to separate file
  • Move richtext types to types folder
  • Add some gql types

How to use

https://www.reddit.com/r/ReturnNewReddit/comments/1vmgvmt/beautiful_right_now_you_can_enjoy_it_too/


r/Littux • • Aug 21 '26

New reddit/d2x update new.reddit.com recovery release v0.4.0

Thumbnail
github.com
12 Upvotes

What's changed

Many speed-ups

  • Listing pages speed up
  • Comments page optimizations (now loads in ~1.1s)
  • Startup speed increase (from around 6s to 3.5s) by background fetch of blocked users and preferences (slow API requests) and only waiting for the main GetAccount GraphQL request

Bugs fixed

  • Use r2 instead of gql for r/popular (faster and fixes the issue with usernames being u/[deleted]. Though awards will no longer appear)
  • Fix submit page bug when no subreddits have been selected
  • Use r2 subreddit info instead of gql. Now, stuff like post flair position will no longer be hardcoded as "right"
  • Author cake day indicator now works again
  • Stop subscribed subreddits fetch from overwriting good state (solves issues like post flair templates not appearing)
  • migrate LanguageSelections to gql-fed
  • Change treeshake options in vite.config.ts

Enhancements

  • REST API requests can now expect a status code, and not throw an error
  • Avoid arctic-shift if possible (if profile curation is disabled)
  • React Redux devtools now work
  • Deduplicated gql requests
  • oauthPipe errors are now logged

GitHub: https://github.com/Littux-Dustux/new-reddit-com/

How to run: https://www.reddit.com/r/ReturnNewReddit/comments/1vmgvmt/beautiful_right_now_you_can_enjoy_it_too/


r/Littux • • Aug 18 '26

New Reddit/D2X bug [new.reddit/d2x bug] Trying to sort posts to the top on a profile returns 400

Post image
6 Upvotes

r/Littux • • Aug 14 '26

New reddit/d2x update new.reddit.com recovery release v1.2.0

Thumbnail
github.com
10 Upvotes

Fixes:

Toast messages are now reduced by default


r/Littux • • Aug 13 '26

[FIXED] New Reddit/D2X bug Crossposting and uploading a video isn't working on New Reddit

5 Upvotes

So I would like to crosspost a post, but after I click on it, it redirects me to the blank submit page.

I can't upload a video of it because it's stuck on 0% too


r/Littux • • Jun 14 '26

New reddit/d2x update New reddit recovery progress: subreddit listing pages now work, with styling

12 Upvotes

r/Littux • • Apr 30 '26

New userscript Reddit native translations userscript (initial release - old reddit only)

7 Upvotes

r/Littux • • Apr 09 '26

New reddit/d2x update New Reddit recovery progress

Thumbnail
gallery
20 Upvotes
  • Search & Home feed: complete functionality
  • Post comments: partial functionality
  • Actions (Vote, subscribe, save etc): Mostly works

r/Littux • • Mar 27 '26

Fuck Spez / Fix Reddit Fix "Processing img <id>..." on Old Reddit

Post image
3 Upvotes

https://greasyfork.org/en/scripts/571318-fix-processing-img-id-on-old-reddit

Features

  • Ultra fast loading
  • Uses mp4 instead of gif: higher quality with lower bandwidth (gif is a shit format)
  • Automatically pauses videos when they go off-screen

r/Littux • • Mar 19 '26

Fuck Spez / Fix Reddit I made the old mod.reddit.com mod mail client work again. You can continue using it by installing a userscript

13 Upvotes

(Originally meant to be posted to r/ModSupport. Posted here since it can't be removed)

Install the Tamper Monkey extension (firefox / chromium), and install the userscript: https://greasyfork.org/en/scripts/570323-mod-reddit-com-revived

Then visit https://mod-reddit-com.netlify.app/mail/all OR self host it by just running a single python file: https://github.com/Littux-Dustux/mod-reddit-com/. The localhost version will be at http://localhost:44444/. Instructions are given on the git repo


Issues

  • The user pane doesn't display karma, profile picture and trophies
  • If on the website and it isn't localhost (self hosted), websockets won't function, so typing indicators in mod mail conversations won't work
  • Toolbox doesn't work (since it won't run on the URL)

    • I'm making a fix for this in my toolbox fork (since development stopped)

Improvements

  • Bug fix: if you archive/highlight/mark read more than 50 conversations at once, it will split it into multiple network requests. You will no longer get an error
  • Performance improvement: Going from "All" to "Inbox" to "New" to "In Progress" etc no longer reloads the page, and immediately loads

FAQ

  • What is the userscript for?

    • It handles the authentication and bypasses CORS policies. It redirects reddit.com/mail/* to the archive page
  • Is the website (netlify) safe?

    • The website only contains an index.html and this file, which redirects all URLs to the same file:

          [[redirects]]
            from = "/*"
            to = "/index.html"
            status = 200
            methods = ["GET"]

      You can self host for maximum safety

  • Why am I getting a white screen?

    • The app crashed for some reason. Please contact me if that happens
  • Why is it stuck at "Waiting for event from userscript"?

    • The userscript crashed or isn't running. Make sure it ran by checking the tampermonkey menu

More Info

Before Reddit shut down mod.reddit.com, I archived the full page source. Since it is a single page application, it only needs to load some JS bundles to display content.

But the complex part isn't that. During the first load, the data for a page is "preloaded" into the window.___r object. Normally, it's done by Reddit's servers. But there is no server to bundle it now, so the inline script on the page does the loading instead, and delays loading of the JS bundles until then. So it has a loading screen now.

Until yesterday, it worked 100% fine until Reddit killed "gql.reddit.com" right in front of me while I was finalizing the archived version. The conversations completely stopped loading. There was a constant error message on the top. It is an API used for mod notes, saved responses and the user pane. The new GraphQL endpoint they use is "gql-fed.reddit.com" in the mobile app. Luckily, I had extracted all the available query information from the mobile app. I was able to map most of the old operations to the new ones.

Except for one (RedditorsInfoByIds), which is used for the user pane. There is no equivalent for it that I can find and I would need to extract data from multiple places to create an equivalent response. And I also don't know how the object looks like (since the dumb me didn't archive it hoping that gql.reddit.com would stay around forever). gql.reddit.com is what powered new.reddit.com (RIP), so after mod.reddit.com was also sunset, there was nothing using it, except ancient reddit app versions.


I said I only had time to work on this after March 30, but I had time the last few days, so I completely used them for this, because otherwise I won't be able to look at mod mails


r/Littux • • Jul 13 '25

YouTube auto-dubbing songs

1 Upvotes

r/Littux • • Jun 27 '25

After 1 year 8 months of being on Reddit, I got banned from a subreddit for the first time

Thumbnail
gallery
1 Upvotes

Basically, I made a joke comment saying "COMMENT DOXXING OP" on a post made by a person on r/SUBREDDITNAME who was responsible for the suicide of the SaveAFox YouTuber. Apparently, that comment was punishable among the many other comments literally just telling OP to k!ll themselves


r/Littux • • Jun 25 '25

i.redd.it archive viewer

1 Upvotes

r/Littux • • May 15 '25

BOT TESTING: currency-bot

1 Upvotes