Twitch sidebar preview

preview live when hover channel in sidebar

// ==UserScript==
// @name               Twitch sidebar preview
// @namespace          https://greasyfork.org/users/821661
// @match              https://www.twitch.tv/*
// @grant              none
// @version            1.0
// @author             hdyzen
// @description        preview live when hover channel in sidebar
// @license            GPL-3.0
// ==/UserScript==
'use strict';

const logInConsole = false;
const previewIfr = true;

function log(...args) {
    if (logInConsole) console.log('[LOG]', ...args);
}

function whenHover(e) {
    if (e.target.nodeName === 'A' && e.target.classList.contains('side-nav-card')) {
        const channelInHover = e.target.href.split('/').at(-1);
        const preview = document.getElementById('preview-sidebar');

        if (preview && preview.dataset.preview !== channelInHover) {
            log(e.target, preview.dataset.preview, channelInHover);

            preview.dataset.preview = channelInHover;
            preview.src = previewIfr ? `https://player.twitch.tv/?channel=${channelInHover}&controls=false&autoplay=true&parent=twitch.tv` : `https://static-cdn.jtvnw.net/previews-ttv/live_user_${channelInHover}-440x248.jpg`;
        }
    }
}

function addPreviewObserver() {
    const dialogLayer = document.getElementsByClassName('online-side-nav-channel-tooltip__body');
    const preview = document.getElementById('preview-sidebar');

    if (dialogLayer.length && !preview) {
        const previewChannel = dialogLayer[0].firstElementChild.textContent.split(' ')[0].toLowerCase();

        log('Added preview');
        dialogLayer[0].insertAdjacentHTML('beforeend', previewIfr ? `<iframe id="preview-sidebar" data-preview="${previewChannel}" src="https://player.twitch.tv/?channel=${previewChannel}&controls=false&autoplay=true&muted=true&parent=twitch.tv">` : `<img id="preview-sidebar" data-preview="${previewChannel}" style="width: 300px; max-width: 300px;" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_${previewChannel}-440x248.jpg">`);
    }
}

document.addEventListener('mouseover', whenHover);

new MutationObserver(addPreviewObserver).observe(document.body, { childList: true, subtree: true });