NOTICE: By continued use of this site you understand and agree to the binding Terms of Service and Privacy Policy.
// ==UserScript==
// @name Better Youtube
// @namespace http://tampermonkey.net/
// @version 0.26
// @description Video list more compact, hide watched videos and more
// @author You
// @match https://www.youtube.com/*
// @icon https://www.youtube.com/s/desktop/47009d78/img/favicon.ico
// @grant none
// @license MIT
// @updateURL https://openuserjs.org/meta/asteriksme/Better_Youtube.meta.js
// @downloadURL https://openuserjs.org/install/asteriksme/Better_Youtube.user.js
// ==/UserScript==
/* jshint esversion: 11 */
(function() {
'use strict';
const getRelativeTimeString = (date, lang = navigator.language) => {
const timeMs = typeof date === "number" ? date : date.getTime();
const deltaSeconds = Math.round((timeMs - Date.now()) / 1000);
const cutoffs = [60, 3600, 86400, 86400 * 7, 86400 * 30, 86400 * 365, Infinity];
const units = ["second", "minute", "hour", "day", "week", "month", "year"];
const unitIndex = cutoffs.findIndex(cutoff => cutoff > Math.abs(deltaSeconds));
const divisor = unitIndex ? cutoffs[unitIndex - 1] : 1;
const rtf = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });
return rtf.format(Math.floor(deltaSeconds / divisor), units[unitIndex]);
};
let running = false;
const addTimestamps = async () => {
if (running || !document.querySelector(".ytp-endscreen-content a .ytp-videowall-still-info-author")) return;
running = true;
const tags = document
.querySelector(".ytp-endscreen-content")
?.querySelectorAll("a:not([data-timestamp-added])");
if (!tags?.length) {
running = false;
return;
}
await Promise.all(
[...tags].map((tag) =>
fetch(tag.href).then((r) => r.text()).then((res) => {
const match = res.match(/publishDate":"([^"]*)"/);
if (!match) return;
const date = new Date(match[1]);
const el = tag.querySelector(".ytp-videowall-still-info-author");
if (!el) return;
el.appendChild(document.createTextNode(` • ${date.toLocaleDateString()} (${getRelativeTimeString(date)})`));
tag.setAttribute("data-timestamp-added", "");
}).catch(() => {})
)
);
running = false;
};
const getStyleEl = (id) => {
let style = document.getElementById(id);
if (!style) {
style = document.createElement("style");
style.id = id;
document.head.appendChild(style);
}
return style;
};
const changeVideosPerRow = () => {
const itemsPerRow = window.innerWidth <= 2000 ? 5 : 6;
const css = `ytd-rich-grid-renderer, ytd-rich-item-renderer, .video-card { --ytd-rich-grid-items-per-row: ${itemsPerRow} !important; }`;
const style = getStyleEl("yt-videos-per-row");
if (style.textContent !== css) style.textContent = css;
};
const removeUselessSection = () => {
const css = "ytd-rich-section-renderer { display: none !important; }";
const style = getStyleEl("yt-hide-sections");
if (style.textContent !== css) style.textContent = css;
};
const removeChannelTrailer = () => {
document.querySelector('[role="main"][page-subtype="channels"] ytd-channel-video-player-renderer video')?.remove();
};
let hideWatched = false;
let scheduled = false;
const svgNS = "http://www.w3.org/2000/svg";
function createSvg({ viewBox, className, paths }) {
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("xmlns", svgNS);
svg.setAttribute("width", "16");
svg.setAttribute("height", "16");
svg.setAttribute("fill", "currentColor");
svg.setAttribute("viewBox", viewBox);
if (className) svg.setAttribute("class", className);
paths.forEach(d => {
const path = document.createElementNS(svgNS, "path");
path.setAttribute("d", d);
svg.appendChild(path);
});
return svg;
}
function createEyeIcon() {
return createSvg({
viewBox: "0 0 16 16",
className: "bi bi-eye",
paths: [
"M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8M1.173 8a13 13 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5s3.879 1.168 5.168 2.457A13 13 0 0 1 14.828 8q-.086.13-.195.288c-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5s-3.879-1.168-5.168-2.457A13 13 0 0 1 1.172 8z",
"M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5M4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0"
]
});
}
function createEyeSlashIcon() {
return createSvg({
viewBox: "0 0 16 16",
className: "bi bi-eye-slash",
paths: [
"M13.359 11.238C15.06 9.72 16 8 16 8s-3-5.5-8-5.5a7 7 0 0 0-2.79.588l.77.771A6 6 0 0 1 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13 13 0 0 1 14.828 8q-.086.13-.195.288c-.335.48-.83 1.12-1.465 1.755q-.247.248-.517.486z",
"M11.297 9.176a3.5 3.5 0 0 0-4.474-4.474l.823.823a2.5 2.5 0 0 1 2.829 2.829zm-2.943 1.299.822.822a3.5 3.5 0 0 1-4.474-4.474l.823.823a2.5 2.5 0 0 0 2.829 2.829",
"M3.35 5.47q-.27.24-.518.487A13 13 0 0 0 1.172 8l.195.288c.335.48.83 1.12 1.465 1.755C4.121 11.332 5.881 12.5 8 12.5c.716 0 1.39-.133 2.02-.36l.77.772A7 7 0 0 1 8 13.5C3 13.5 0 8 0 8s.939-1.721 2.641-3.238l.708.709zm10.296 8.884-12-12 .708-.708 12 12z"
]
});
}
function renderWatchButton(btn, hideWatched) {
// clear previous content
btn.replaceChildren();
const icon = hideWatched ? createEyeIcon() : createEyeSlashIcon();
const span = document.createElement("span");
span.style.marginLeft = "6px";
span.style.fontSize = "12px";
span.textContent = hideWatched ? "Show watched" : "Hide watched";
btn.appendChild(icon);
btn.appendChild(span);
}
function ensureToggleButton() {
if (document.getElementById('by-hide-watched-btn')) return;
const btn = document.createElement('button');
btn.id = 'by-hide-watched-btn';
btn.type = 'button';
renderWatchButton(btn, false);
btn.title = 'Hide watched videos';
Object.assign(btn.style, {
position: 'fixed',
display: 'flex',
gap: 4,
alignItems: 'center',
top: '13px',
right: '245px',
zIndex: 999999,
fontSize: '18px',
borderRadius: '6px',
padding: '6px 10px',
border: '1px solid #666',
background: '#222',
color: '#fff',
cursor: 'pointer',
opacity: '0.85'
});
btn.addEventListener('mouseenter', () => { btn.style.opacity = '1'; });
btn.addEventListener('mouseleave', () => { btn.style.opacity = '0.85'; });
btn.addEventListener('click', () => {
hideWatched = !hideWatched;
renderWatchButton(btn, hideWatched);
btn.title = hideWatched ? 'Show watched videos' : 'Hide watched videos';
process();
});
document.addEventListener('fullscreenchange', () => {
btn.style.display = Boolean(document.fullscreenElement) ? 'none' : 'flex';
});
document.body.appendChild(btn);
}
function tagAndStyleWatched() {
const MIN_PROGRESS_PERCENT = 15;
document.querySelectorAll('yt-thumbnail-overlay-progress-bar-view-model, ytd-thumbnail-overlay-resume-playback-renderer').forEach(pb => {
const seg = pb.querySelector('.ytThumbnailOverlayProgressBarHostWatchedProgressBarSegment, .ytd-thumbnail-overlay-resume-playback-renderer');
let qualifies = false;
if (seg) {
const styleAttr = seg.getAttribute('style') || '';
const m = styleAttr.match(/width\s*:\s*([\d.]+)%/i);
if (m) {
const pct = parseFloat(m[1]);
if (!isNaN(pct) && pct >= MIN_PROGRESS_PERCENT) {
qualifies = true;
}
}
}
const thumbVM = pb.closest('yt-thumbnail-view-model');
const rich = pb.closest('ytd-rich-item-renderer');
if (!rich) return;
if (qualifies) {
rich.setAttribute('data-better-youtube-watched', '1');
if (thumbVM) {
const img = thumbVM.querySelector('.ytThumbnailViewModelImage');
if (img && !img.dataset._betterYoutubeStyled) {
img.style.filter = 'grayscale(100%) contrast(50%)';
img.dataset._betterYoutubeStyled = '1';
}
}
} else {
rich.removeAttribute('data-better-youtube-watched');
if (thumbVM) {
const img = thumbVM.querySelector('.ytThumbnailViewModelImage');
if (img && img.dataset._betterYoutubeStyled) {
img.style.filter = '';
delete img.dataset._betterYoutubeStyled;
}
}
}
});
}
function applyHideShow() {
const watched = document.querySelectorAll('ytd-rich-item-renderer[data-better-youtube-watched="1"]');
watched.forEach(rich => {
rich.style.display = hideWatched ? 'none' : '';
});
}
function removeFirstColumnAttr() {
document.querySelectorAll('ytd-rich-item-renderer[is-in-first-column]').forEach(el => {
el.removeAttribute('is-in-first-column');
});
}
function process() {
tagAndStyleWatched();
removeFirstColumnAttr();
applyHideShow();
}
function scheduleProcess() {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
process();
});
}
const init = () => {
ensureToggleButton();
process();
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
setInterval(removeFirstColumnAttr, 5000);
const resetFont = () => {
document.querySelectorAll('.ytLockupMetadataViewModelTitle,.ytBadgeShapeText').forEach((el) => { el.style.fontStretch = '100%'; });
};
// --- observer with debounce ---
let obsScheduled = false;
const runAll = () => {
obsScheduled = false;
removeUselessSection();
removeChannelTrailer();
changeVideosPerRow();
addTimestamps();
resetFont();
};
const observer = new MutationObserver(() => {
if (obsScheduled) return;
obsScheduled = true;
// batch multiple mutations into one run
requestAnimationFrame(() => {
runAll();
scheduleProcess();
});
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
window.addEventListener("resize", changeVideosPerRow);
// initial run
runAll();
})();