Skip to content

Instantly share code, notes, and snippets.

@danthemango
Last active July 18, 2024 00:26
Show Gist options
  • Save danthemango/03431b6360ef6df6ce6bad67ab33b3b3 to your computer and use it in GitHub Desktop.
Save danthemango/03431b6360ef6df6ce6bad67ab33b3b3 to your computer and use it in GitHub Desktop.
Userscript to keep youtube chat to "live chat" (instead of "top chat")
// ==UserScript==
// @name YouTube Persistent Live Chat
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Try to keep youtube livestream chat in "live chat" or "live chat replay" mode
// @include https://www.youtube.com/*
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant none
// ==/UserScript==
(function() {
'use strict';
const timeout = 100; // milliseconds between attempt
let timeoutID;
// returns the livechat iframe document
function getChatDoc() {
const theFrame = document.querySelector("#chat iframe");
if (theFrame && theFrame.contentWindow && theFrame.contentWindow.document) {
return theFrame.contentWindow.document;
}
}
// returns true if we have a live chat header
function isLiveChat() {
const frameDoc = getChatDoc();
const theHeader = (frameDoc || document).querySelector('div.yt-dropdown-menu#label-text')
if (!theHeader) {
return false;
}
return /live chat/i.test(theHeader.innerText);
}
// keep trying the clicker every few milliseconds until we have the live chat header
function tryClicker() {
if (isLiveChat()) {
// stop trying on success
clearTimeout(timeoutID);
} else {
// else, try again and reset timer
liveChatClick();
timeoutID = setTimeout(tryClicker, timeout);
}
}
// clicks the "live chat" or "live chat replay" button
function liveChatClick() {
const frameDoc = getChatDoc();
const theitems = (frameDoc || document).querySelectorAll('div.yt-dropdown-menu.item')
for (const item of theitems) {
if (/live chat/i.test(item.innerText)) {
item.click();
}
}
}
window.addEventListener("resize", tryClicker);
window.addEventListener("load", tryClicker);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment