Skip to content

Instantly share code, notes, and snippets.

@RoguedBear
Last active August 19, 2022 15:54
Show Gist options
  • Save RoguedBear/56758693577fa324b1556e94d68ac6d3 to your computer and use it in GitHub Desktop.
Save RoguedBear/56758693577fa324b1556e94d68ac6d3 to your computer and use it in GitHub Desktop.
Enables Youtube's Dark Mode using cookie

EnableYTDarkMode

This script changes Youtube's theme to dark mode by changing preferences via cookie.

Earlier, you could change YT's theme instantly by clicking the theme button.

A few weeks back, Youtube changed their site so when you click the dark mode button, it now reloads the page to change the theme instead of doing it instantly like it used to.

My browser clears cookies frequently, so I find this extra reload + waiting time very annoying

So i automated it, when youtube loads and it doesnt detect the dark mode preference value in the cookie, the script adds it and forces a reload.

Much tolerable than manually clicking the dark mode buttong and waiting for it to finish reloading ;)

// ==UserScript==
// @name Enable Youtube's Inbuilt Dark Mode (using cookies)
// @version 0.1
// @description Enable Youtube's inbuilt Dark Mode; Useful when you frequently clear cookies
// @author RoguedBear
// @match https://*.youtube.com/*
// @grant none
// @noframes
// @supportURL https://gist.github.com/RoguedBear/56758693577fa324b1556e94d68ac6d3
// ==/UserScript==
(function () {
"use strict";
function setCookie(cName, cValue, expDays) {
let date = new Date();
date.setTime(date.getTime() + expDays * 24 * 60 * 60 * 1000);
const expires = "expires=" + date.toUTCString();
document.cookie =
cName + "=" + cValue + "; " + expires + "; path=/; domain=.youtube.com";
console.log(cName + "=" + cValue + "; " + expires + "; path=/");
}
// cookie to json
// https://stackoverflow.com/a/30138647
function cookieToJSON() {
var cookie = document.cookie;
var output = {};
cookie.split(/\s*;\s*/).forEach(function (pair) {
pair = pair.split(/\s*=\s*/);
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair.splice(1).join("="));
output[name] = value;
});
return output;
}
const cookies = cookieToJSON();
if (!("PREF" in cookies) || cookies.PREF.indexOf("f6=400") === -1) {
setCookie("PREF", "tz=UTC&f6=400", 1);
window.location.reload();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment