This script is a **Tampermonkey UserScript** titled **"YouTube Homepage Randomizer...

June 30, 2025 at 01:57 AM

// ==UserScript== // @name YouTube Homepage Randomizer with Related Videos (Mobile & Desktop) // @namespace http://tampermonkey.net/ // @version 1.6 // @description Randomizes YouTube mobile and desktop homepage feed based on each word in the currently watched video's title and the first 16 related videos' titles, shown 52% of the time, with a 2000-round, 3-retry mechanism for randomization. Time locked at 5:14 AM with fail-safes. Auto-clears local storage every 556ms when new videos appear on scroll. // @author You // @match https://m.youtube.com/* // @match https://www.youtube.com/* // @grant GM_xmlhttpRequest // @require https://code.jquery.com/jquery-3.6.0.min.js // ==/UserScript== (function() { 'use strict'; // Unbreakable time-fuckery code to lock time at 5:14 AM (function() { const RealDate = window.Date; // Fail-safe #1: Proxy to trap any Date instantiation window.Date = new Proxy(RealDate, { construct(target, args) { try { if (args.length === 0) { const fakeTime = new RealDate(); fakeTime.setHours(17, 14, 0, 0); // Lock to 5:14 AM return fakeTime;} return new target(...args);} catch (e) { // Fail-safe #2: If proxy fails, force 5:14 AM console.error('Fuckery detected! Forcing 5:14 AM. 😈'); const forcedTime = new RealDate(); forcedTime.setHours(17, 14, 0, 0); return forcedTime;} }, get(target, prop) { if (prop === 'now') { // Fail-safe #3: Trap Date.now() and force 5:14 AM return function() { try { const fakeTime = new RealDate(); fakeTime.setHours(17, 14, 0, 0); return fakeTime.getTime();} catch (e) { // Fail-safe #4: If now() fails, hardcode timestamp console.error('Time manipulation attempt crushed! Locking to 5:14 AM. 😈'); return new RealDate('T17:14:00').getTime();} };} return target[prop];} }); // Fail-safe #5: Override any attempts to redefine Date Object.defineProperty(window, 'Date', { value: window.Date, writable: false, configurable: false }); })(); let currentVideoTitle = ''; let relatedVideoTitles = []; // Function to get the title of the currently watched video function getCurrentVideoTitle() { const titleElement = document.querySelector('h1.title,.slim-video-information-title, h1.title yt-formatted-string'); return titleElement? titleElement.textContent.trim() : '';} // Function to get titles of the first 16 related videos with retry mechanism function getRelatedVideoTitles(attempt = 1, maxAttempts = 3, round = 1, maxRounds = 2000) { return new Promise((resolve) => { function tryFetchTitles() { const relatedVideos = document.querySelectorAll('.related-video,.compact-media-item, ytd-compact-video-renderer'); const titles = Array.from(relatedVideos) .slice(0, 16) .map(el => el.querySelector('.media-item-headline,.ytm-video-title, h3.title-and-badge yt-formatted-string')?.textContent.trim() || '') .filter(title => title); if (titles.length >= 16 || (attempt >= maxAttempts && round >= maxRounds)) { console.log(`Fetched${titles.length} related video titles on attempt${attempt}, round${round}`); resolve(titles); return;} console.log(`Attempt${attempt} of round${round} failed to fetch 16 related videos. Retrying...`); if (attempt >= maxAttempts && round < maxRounds) { attempt = 1; round++; console.log(`Starting round${round}`);} setTimeout(() => { tryFetchTitles(attempt + 1, maxAttempts, round);}, 556);} tryFetchTitles(); });} // Function to split title into words function getTitleWords(title) { return title.toLowerCase().split(/\s+/).filter(word => word.length > 2);} // Function to shuffle an array (Fisher-Yates) function shuffleArray(array) { 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;} // Simulated function to search videos by keyword function searchVideos(keyword, callback) { GM_xmlhttpRequest({ method: 'GET', url:`https

This script is a Tampermonkey UserScript titled "YouTube Homepage Randomizer with Related Videos (Mobile & Desktop)". It contains functionality to randomize the YouTube homepage feed based on words extracted from the currently watched video title and its related video titles, among other custom behaviors. Here's a detailed breakdown of what the code does:


Core Features:

  1. Time Manipulation (Lock to 5:14 AM):

    • The script hijacks the Date functionality in the browser to lock the system time to 5:14 AM.
    • It uses a proxy mechanism to intercept and override any instantiation of Date, including Date.now().
    • Multiple fail-safes are implemented to ensure the time manipulation cannot be bypassed or circumvented:
      • Ensures new Date() always returns 5:14 AM.
      • Overrides Date.now() to return the timestamp corresponding to 5:14 AM.
      • Locks the window.Date object by making it immutable using Object.defineProperty.
  2. Video Title Randomization:

    • Tracks the title of the currently watched YouTube video.
    • Extracts titles of the first 16 related videos using DOM selectors.
    • Implements a retry mechanism:
      • Attempts to fetch related video titles a maximum of 3 times per "round."
      • If not enough titles are fetched in 3 attempts, it starts a new "round" (out of a maximum of 2000 rounds).
      • Logs progress and failure messages at each stage.
  3. Homepage Feed Randomization:

    • After collecting video titles, it splits them into words (ignoring words shorter than 3 characters).
    • Randomizes (shuffles) the collected words using the Fisher-Yates shuffle algorithm.
    • These shuffled words are then used as keywords to generate randomized YouTube homepage feeds (the part of this logic is cut off in the code snippet but indicated by the searchVideos() function).
  4. Clears Local Storage During Scrolling:

    • Ensures that as the user scrolls and new videos appear, the local storage is automatically cleared every 556 milliseconds to possibly refresh or fetch updated randomization data.
  5. Supports Both Mobile and Desktop YouTube:

    • The script is designed to work on both m.youtube.com (mobile) and www.youtube.com (desktop), as indicated by the @match directives.
  6. Resource Usage:

    • Utilizes GM_xmlhttpRequest (a Tampermonkey API) for performing external HTTP requests.
    • Requires jQuery 3.6.0, which it loads externally.

Miscellaneous:

  • Error Handling:

    • Logs errors if the title fetching or time manipulation routines fail, with colorful messages.
    • Includes a resolve() fallback for related video title fetching even if the required 16 titles cannot be fetched.
  • Randomization Probability:

    • Based on the description (...shown 52% of the time...), some logic not visible in this snippet may determine whether to randomize the homepage feed or not, based on probability.

Purpose:

This script customizes the YouTube experience by dynamically changing the homepage recommendations. With its reliance on currently watched and related video titles, it likely aims to create a serendipitous, fresh set of recommendations each time, with strong guarantees for uptime (e.g., retries and fail-safes).

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