Pinterest - Enhanced Page Title with Username and Alt Text

Replace the page title with the user profile name and auto alt text on Pinterest (removes emojis from name) - Optimized for performance

目前為 2025-03-16 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Pinterest - Enhanced Page Title with Username and Alt Text
// @version      2.7
// @description  Replace the page title with the user profile name and auto alt text on Pinterest (removes emojis from name) - Optimized for performance
// @author       wolffgang
// @match        *://*.pinterest.com/*
// @grant        none
// @namespace 
// ==/UserScript==

(function() {
    'use strict';

    let observer = null; // Declare observer outside the function
    let titleReplaced = false;

    function replaceTitle() {
        if (titleReplaced) return; // Prevent further executions

        let usernameElement = null;
        let profileNameElement = null;
        let username = null;
        let fullName = null;
        let autoAltText = null;
        let pinId = null;

        // Extract pinId from URL
        const url = window.location.href;
        const pinIdMatch = url.match(/pin\/(\d+)/);
        if (pinIdMatch && pinIdMatch[1]) {
            pinId = pinIdMatch[1];
        }

        // Extract data from __PWS_INITIAL_PROPS__ script tag
        const scriptTag = document.getElementById('__PWS_INITIAL_PROPS__');
        if (scriptTag) {
            try {
                const jsonData = JSON.parse(scriptTag.textContent);
                console.log('JSON Data:', jsonData); // Log the entire JSON data for inspection

                fullName = jsonData?.initialReduxState?.user?.currentUser?.full_name;
                username = jsonData?.initialReduxState?.user?.currentUser?.username;

                // Extract auto_alt_text from the JSON data
                if (pinId) {
                    autoAltText = jsonData?.initialReduxState?.pins?.[pinId]?.auto_alt_text;
                }

                console.log('Extracted autoAltText:', autoAltText); // Log the extracted autoAltText

            } catch (error) {
                console.error('Error parsing JSON:', error);
            }
        }

        // Check if it's a pin page
        if (window.location.href.match(/pin\/\d+/)) {
            profileNameElement = document.querySelector('div[data-test-id="creator-profile-name"] div.X8m.zDA.IZT.tBJ.dyH.iFc.j1A.swG');
            usernameElement = document.querySelector('a[data-test-id="creator-profile-link"]');
        }
        // Check if it's a profile page
        else if (window.location.href.match(/\/[a-zA-Z0-9]+\/$/)) {
            profileNameElement = document.querySelector('div[data-test-id="profile-name"] div.zI7.iyn.Hsu[style*="display: inline"]');
            const urlParts = window.location.pathname.split('/');
            username = urlParts[1];
        }

        let title = '';

        if (fullName && username) {
            title = `${fullName} (${username})`;
        } else if (profileNameElement && usernameElement) {
            const displayedUsername = profileNameElement.innerText;
            const linkUsername = usernameElement.getAttribute('href').replace(/\//g, '');
            title = `${displayedUsername} (${linkUsername})`;
        } else if (profileNameElement && username) {
            const displayedUsername = profileNameElement.innerText;
            title = `${displayedUsername} (${username})`;
        }

        if (autoAltText) {
            title += ` - ${autoAltText}`;
        }

        document.title = title;

        // Post-processing: Remove emojis from document.title
        document.title = document.title.replace(/[\u2000-\u3300]|\uD83C[\uD000-\uDFFF]|\uD83D[\uD000-\uDFFF]|\uD83E[\uD000-\uDFFF]/g, '');

        titleReplaced = true; // Set flag to prevent further executions
        if (observer) {
            observer.disconnect(); // Disconnect observer
            console.log('MutationObserver disconnected.');
        }
    }

    // Debounce function
    function debounce(func, delay) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), delay);
        };
    }

    const debouncedReplaceTitle = debounce(replaceTitle, 250); // Debounce by 250ms

    // Observe changes in the DOM to handle dynamic content loading
    observer = new MutationObserver(debouncedReplaceTitle);
    observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: true, // Observe attribute changes
        characterData: true // Observe text content changes
    });

    // Initial call to handle cases where the elements are already loaded
    debouncedReplaceTitle();

    // Reduced aggressive retries
    const interval = setInterval(() => {
        if (titleReplaced) {
            clearInterval(interval);
            return;
        }
        debouncedReplaceTitle();
    }, 2000); // Retry every 2 seconds

    // Stop the interval after a certain amount of time
    setTimeout(() => {
        clearInterval(interval);
        if (!titleReplaced && observer) {
            observer.disconnect();
            console.log('MutationObserver disconnected due to timeout.');
        }
    }, 5000); // Retry for 5 seconds
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址