The provided code is a Tampermonkey Userscript titled **"YouTube Time-Locked...

June 30, 2025 at 02:39 AM

// ==UserScript== // @name YouTube Time-Locked Homepage Randomizer // @namespace http://tampermonkey.net/ // @version 1.2 // @description Locks YouTube homepage feed to mimic tracking state at 5:14 AM for each US time zone, with randomization based on last watched video and categories. // @match https://www.youtube.com/* // @match https://m.youtube.com/* // @grant GM_xmlhttpRequest // @run-at document-idle // ==/UserScript== (function() { 'use strict'; const LS_WORDS_KEY = 'yt_randomizer_title_words'; const TARGET_TIME = '05:14:00'; // 5:14 AM const US_TIMEZONES = { 'PST': -8, // Pacific 'MST': -7, // Mountain 'CST': -6, // Central 'EST': -5 // Eastern}; // Categories/keywords for randomization const CATEGORY_KEYWORDS = { 'audio_commentary': ['audio', 'commentary', 'commentaries', 'review'] }; // Fetch server time to determine current US timezone time function getCurrentTimeInTimezone(offset) { const now = new Date(); const utc = now.getTime() + (now.getTimezoneOffset() * 60000); const localTime = new Date(utc + (3600000* offset)); return localTime.toTimeString().split(' ')[0]; // Format: HH:MM:SS} // Check if current time matches 5:14 AM in any US timezone function isTargetTime() { return Object.values(US_TIMEZONES).some(offset => { return getCurrentTimeInTimezone(offset).startsWith(TARGET_TIME); });} // Simulate feed state at 5:14 AM by fetching homepage data function fetchHomepageData(callback) { GM_xmlhttpRequest({ method: 'GET', url: 'https://www.youtube.com/', onload: function(response) { if (response.status === 200) { callback(response.responseText);} else { console.log('YouTube Randomizer: Failed to fetch homepage data, fuck it.');} }, onerror: function() { console.log('YouTube Randomizer: Error fetching homepage, shit happens.');} });} // Observe URL changes in SPA let lastUrl = location.href; new MutationObserver(() => { if (location.href!== lastUrl) { lastUrl = location.href; setTimeout(handlePageChange, 700);} }).observe(document, { childList: true, subtree: true }); // Initial run setTimeout(handlePageChange, 1000); function handlePageChange() { if (isWatchPage()) { extractAndStoreTitleWords();} if (location.pathname === '/' || (location.pathname === '/feed/you' && isMobile())) { setTimeout(() => { if (isTargetTime()) { randomizeHomepageFeed();} else { // Force feed to mimic 5:14 AM state fetchHomepageData((data) => { console.log('YouTube Randomizer: Fetched homepage data to mimic 5:14 AM, let’s fuck shit up.'); randomizeHomepageFeed(); });} }, 500);} } function isWatchPage() { return location.pathname.startsWith('/watch');} function isMobile() { return location.hostname === 'm.youtube.com';} function extractAndStoreTitleWords() { let titleEl = document.querySelector('h1.style-scope.ytd-watch-metadata yt-formatted-string') || document.querySelector('h1#title.style-scope.ytd-watch-metadata') || document.querySelector('.watch-title h1'); if (!titleEl) { console.log('YouTube Randomizer: Couldn’t find the damn title element.'); return;} const words = titleEl.textContent.split(/\s+/) .map(w => w.replace(/[^\w]/g, '').toLowerCase()) .filter(w => w.length > 2); if (!words.length) { console.log('YouTube Randomizer: No fucking useful words in the title.'); return;} const prevWords = localStorage.getItem(LS_WORDS_KEY) || '[]'; const currentWords = JSON.stringify(words); if (currentWords!== prevWords) { localStorage.setItem(LS_WORDS_KEY, currentWords); console.log('YouTube Randomizer: Stored title words, ready to fuck with the feed:', words);} else { console.log('YouTube Randomizer: Title words are the same, no shit to update.');} } function randomizeHomepageFeed() { const storedWords = localStorage.getItem(LS_WORDS_KEY); const prevVideoWords = storedWords? JSON.parse(storedWords) : []; const feed = getFeedContainer(); if (!feed) { console.log('YouTube Randomizer: Feed container is fucking missing.'); return;} const allItems = Array.from(feed.children).filter(item => item.id!== 'feed-placeholder'); if (allItems.length === 0) { console.log('YouTube Randomizer: No damn items to randomize.'); return;} const prevVideoRelatedItems = []; const audioCommentaryItems = []; const unmatchedItems = []; allItems.forEach(item => { const link = item.querySelector('#video-title') || item.querySelector('a[href^="/watch"]'); const channelLink = item.querySelector('.ytd-channel-name a') || item.querySelector('.yt-formatted-string'); const titleText = (link && link.textContent || '').toLowerCase(); const channelText = (channelLink && channelLink.textContent || '').toLowerCase(); const combinedText = titleText + ' ' + channelText; const isPrevVideoRelated = prevVideoWords.some(word => combinedText.includes(word)); const audioKeywords = CATEGORY_KEYWORDS['audio_commentary']; const isAudioCommentary = audioKeywords.some(keyword => combinedText.includes(keyword)); if (isPrevVideoRelated) { prevVideoRelatedItems.push(item);} else if (isAudioCommentary) { audioCommentaryItems.push(item);} else { unmatchedItems.push(item);} }); console.log(`YouTube Randomizer: Found${allItems.length} fucking items. Prev video:${prevVideoRelatedItems.length}, Audio Commentary:${audioCommentaryItems.length}, Unmatched:${unmatchedItems.length}`); shuffleArray(prevVideoRelatedItems); shuffleArray(audioCommentaryItems); shuffleArray(unmatchedItems); const totalItems = allItems.length; const targetPrevCount = Math.ceil(totalItems* 0.59); const targetAudioCount = Math.ceil(totalItems* 0.39); const topPrev = prevVideoRelatedItems.slice(0, targetPrevCount); const topAudio = audioCommentaryItems.slice(0, targetAudioCount); const restPrev = prevVideoRelatedItems.slice(targetPrevCount); const restAudio = audioCommentaryItems.slice(targetAudioCount); const remainingItemsShuffled = shuffleArray([...restPrev, ...restAudio, ...unmatchedItems]); const newOrder = shuffleArray([...topPrev, ...topAudio]).concat(remainingItemsShuffled); allItems.forEach(item => item.remove()); newOrder.forEach(item => feed.appendChild(item)); console.log('YouTube Randomizer: Feed fucked up and randomized, enjoy the chaos.');} function getFeedContainer() { return document.querySelector('ytd-rich-grid-renderer div#contents') || document.querySelector('ytd-browse div#contents') || document.querySelector('ytm-browse.tabContainer ytm-section-list-renderer div#contents');} function shuffleArray(arr) { const array = [...arr]; for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]];} return array;} (function observeInfiniteScroll() { const feed = getFeedContainer(); if (!feed) { return setTimeout(observeInfiniteScroll, 1000);} const observerOptions = { childList: true, subtree: false}; new MutationObserver(mutations => { let addedNodes = false; for (const mutation of mutations) { if (mutation.addedNodes.length > 0) { addedNodes = true; break;} } if (addedNodes) { setTimeout(() => { if (isTargetTime()) { randomizeHomepageFeed();} else { fetchHomepageData(() => { console.log('YouTube Randomizer: Refetched homepage data for infinite scroll, let’s keep fucking with it.'); randomizeHomepageFeed(); });} }, 300);} }).observe(feed, observerOptions); console.log('YouTube Randomizer: Watching the feed like a fucking hawk for infinite scroll.'); })(); console.log('YouTube Randomizer: Script loaded, ready to fuck shit up!'); })();

The provided code is a Tampermonkey Userscript titled "YouTube Time-Locked Homepage Randomizer", and it performs the following tasks:

Purpose:

The script modifies and randomizes the YouTube homepage feed, mimicking a static "locked state" of the feed as it would appear at 5:14 AM, based on the user's timezone in the US time zones. This behavior is coupled with randomness based on the user's viewing history, specifically targeting categories like "audio commentary" and keywords derived from titles of previously watched videos.


Key Features:

  1. Time-Zone Based Behavior:

    • The script determines whether the current time matches 5:14 AM in any US timezone (PST, MST, CST, EST).
    • It uses this time logic to decide whether to randomize or alter the homepage feed dynamically.
  2. Homepage Feed Randomization:

    • It fetches the YouTube homepage feed content using GM_xmlhttpRequest (via Tampermonkey's granted permissions).
    • It categorizes videos using the following logic:
      • Videos related to the user's last watched video's title words.
      • Videos that fit into specific categories, such as "audio commentary," determined via predefined keywords.
    • It reorganizes and randomizes the feed, prioritizing related and categorized content while maintaining an element of "chaotic randomness."
  3. User Behavior Tracking:

    • The script observes when a user watches a video (by detecting /watch URLs).
    • It extracts key words from the watched video's title and stores them in localStorage, which is later used for randomizing the homepage feed to prioritize relevant content.
  4. Single Page Application (SPA) URL Observation:

    • Since YouTube operates as a single-page application (SPA), the script monitors URL changes (e.g., navigating between videos or the homepage) using a MutationObserver.
    • It triggers handlePageChange to ensure the feed randomization logic is executed on-the-fly.
  5. Infinite Scroll Handling:

    • The script also monitors the infinite scroll behavior of the homepage feed to apply its randomization logic to new videos loaded dynamically.
  6. Mobile Compatibility:

    • The script handles both desktop (youtube.com) and mobile (m.youtube.com) versions of YouTube.
  7. Randomization Algorithm:

    • Videos are shuffled using a shuffleArray function to create a mixture of prioritized (categorized and related) and general content.
    • Specific proportions of the feed are allocated to videos from different categories (e.g., 59% related videos, 39% categorized content).

Core Functionalities Explained:

  1. Time Lock and Target Time Check (isTargetTime):

    • The function isTargetTime determines whether the current local time matches 5:14 AM in any US timezone.
    • The time in each timezone is computed using the getCurrentTimeInTimezone function with timezone-specific offsets.
    • If the time doesn't match, the script tries to simulate the homepage state as it would have appeared at 5:14 AM.
  2. Homepage Feed Fetching and Handling:

    • The script fetches the current homepage feed using an HTTP request (GM_xmlhttpRequest).
    • It parses the feed, categorizes the videos, and randomizes their order.
  3. Keyword Extraction from Watched Videos:

    • When a user is on a /watch page (indicating they are watching a video), the script extracts the video's title.
    • It analyzes the title to break it into unique, useful keywords (words longer than 2 characters).
    • These keywords are stored in localStorage for use in prioritizing videos that are related to the last watched video.
  4. Feed Container Hijacking:

    • The script identifies the <div> elements containing YouTube's homepage feed using various selectors (ytd-rich-grid-renderer, etc.).
    • It manipulates the child elements of the container to reorder and inject new content dynamically.
  5. Infinite Scroll Support:

    • YouTube's feed loads more videos as the user scrolls down.
    • The script uses another MutationObserver to detect when new videos are added (via infinite scroll) and applies its randomization function to maintain a consistent "locked" state of the feed.

Console Logs:

The script is verbose in logging its operations to the console. For example:

  • It logs whether relevant content was found and categorized.
  • It informs about failed attempts to parse or manipulate elements.
  • Debugging messages contain explicit descriptions of actions, written informally (e.g., "let’s fuck shit up").

Design Decisions:

  1. Feed State Randomization:

    • The feed appears dynamically sorted and categorized without entirely ignoring randomness, creating a structured but unique homepage experience.
  2. Custom Categorization:

    • Only one category is explicitly implemented ("audio commentary"), but the script allows for more categories to be added.
  3. 5:14 AM Locking Behavior:

    • Emulating a static snapshot of the homepage from a specific time, adjusted to the user's timezone, provides an unchanging browsing experience tied to an arbitrary timestamp.
  4. LocalStorage for Persistence:

    • Title words from recently watched videos are persisted across sessions using localStorage.

Conclusion:

This script transforms YouTube's homepage feed by enforcing a randomized but deterministic layout tied to a specific state. It prioritizes related videos and categorized content based on user behavior, simulating the feed at 5:14 AM while injecting randomness for variety. It ensures compatibility with YouTube's SPA nature and supports infinite scroll.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node