GMGN-MEME_BLANK

将页面列表中的链接设置为新窗口打开

// ==UserScript==
// @name         GMGN-MEME_BLANK
// @namespace    http://tampermonkey.net/
// @version      1.0.2
// @description  将页面列表中的链接设置为新窗口打开
// @author       nosora
// @match        https://gmgn.ai/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=gmgn.ai
// @run-at       document-start
// @license      MIT
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 一个函数来设置链接为新窗口打开
    function setLinksToOpenInNewTab() {
        // 检查页面内所有可能是链接的元素
        const links = document.querySelectorAll('a, [onclick]');

        links.forEach(link => {
            if (link.tagName === 'A') {
                // 普通链接
                link.setAttribute('target', '_blank');
            } else if (link.hasAttribute('onclick')) {
                // 处理可能通过 onclick 打开的链接
                const onclickContent = link.getAttribute('onclick');
                if (onclickContent.includes('window.open')) {
                    link.setAttribute('onclick', onclickContent.replace('window.open', 'window.open.bind(window, undefined, "_blank")'));
                } else {
                    link.setAttribute('onclick', `${onclickContent}; window.open(this.href, '_blank');`);
                }
            }
        });
        console.log('所有链接已设置为新窗口打开');
    }

    // 检测 URL 是否以 /meme 开头
    function isOnMemePage() {
        return window.location.pathname.startsWith('/meme');
    }

    // 初始化脚本逻辑
    function init() {
        if (isOnMemePage()) {
            setLinksToOpenInNewTab();
        }
    }

    // 初次执行
    init();

    // 如果页面内容动态加载,监控 DOM 变化
    const observer = new MutationObserver(() => {
        if (isOnMemePage()) {
            setLinksToOpenInNewTab();
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });

    // 监听 URL 变化(对于SPA单页应用)
    window.addEventListener('popstate', () => {
        if (isOnMemePage()) {
            console.log('popstate事件:URL变化,重新初始化脚本');
            init();
        }
    });

    window.addEventListener('hashchange', () => {
        if (isOnMemePage()) {
            console.log('hashchange事件:URL变化,重新初始化脚本');
            init();
        }
    });
})();