Wis / ChatGPT browser tab/window title updater

// ==UserScript==
// @name         ChatGPT browser tab/window title updater
// @namespace    http://tampermonkey.net/
// @version      2024-04-29
// @description  ChatGPT website does not set the title of the tab/window to current chat title, the tab title stays "ChatGPT" and doesn't change, this user script sets it.
// @author       Wis (wis.am / github.com/wis)
// @license      GPL-3.0-only
// @match        https://chat.openai.com/**
// @icon         https://www.google.com/s2/favicons?sz=64&domain=chat.openai.com
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function () {
    function updateTitle() {
        var currentTitle = document.querySelector('.bg-token-sidebar-surface-secondary a[href^="/c/"]').textContent;
        if (document.title !== currentTitle) {
            document.title = currentTitle;
        }
    }

    updateTitle();

    var startInterval = () => setInterval(() => {
        window.requestIdleCallback(updateTitle);
    }, 1000);

    var intervalID = startInterval();

    function handleVisibilityChange() {
        if (document.visibilityState === 'visible') {
            intervalID = startInterval();
        } else if (document.visibilityState === 'hidden') {
            clearInterval(intervalID);
        }
    }

    document.addEventListener('visibilitychange', handleVisibilityChange);
})();