Append Hostname to Window Title

Append the domain name of the site to the window title. Helps offer a hint to tools like AHK so that they can identify the site loaded.

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Append Hostname to Window Title
// @namespace    https://greasyfork.org/users/77886
// @version      0.5
// @description  Append the domain name of the site to the window title. Helps offer a hint to tools like AHK so that they can identify the site loaded.
// @author       muchtall
// @include      *://*/*
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Function to ensure title element exists and append hostname
    function ensureTitleAndAppendHostname() {
        let titleElement = document.querySelector('title');
        if (!titleElement) {
            titleElement = document.createElement('title');
            document.head.appendChild(titleElement);
        }
        document.title = (document.title || 'Untitled') + " - (" + window.location.hostname + ")";
    }

    // Set the window title on page load
    window.addEventListener('load', ensureTitleAndAppendHostname);

    // Workaround for sites that change the title after page load
    setTimeout(function() {
        let target = document.querySelector('title');
        if (!target) {
            target = document.createElement('title');
            document.head.appendChild(target);
        }
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                const re = new RegExp(" - \\(" + window.location.hostname + "\\)$");
                if (!re.test(document.title)) {
                    console.log('Title before "%s"', document.title);
                    document.title = (document.title || 'Untitled') + " - (" + window.location.hostname + ")";
                    console.log('Title after "%s"', document.title);
                }
            });
        });
        const config = {
            childList: true,
        };
        observer.observe(target, config);
    }, 100);
})();