更好访问gcc

根据配置自动替换域名并修改页面资源引用

// ==UserScript==
// @name         更好访问gcc
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  根据配置自动替换域名并修改页面资源引用
// @author       LinXingJun
// @match        *://nc.gcc.edu.cn/*
// @match        *://nic.gcc.edu.cn/*
// @match        *://www-cnki-net.vpn.gcc.edu.cn:*/*
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    // 配置重定向规则(示例格式)
    const redirect_url = {
        'nc.gcc.edu.cn': 'nic.gcc.edu.cn',
        'www-cnki-net.vpn.gcc.edu.cn':'www-cnki-net-s.vpn.gcc.edu.cn'
    };

    // 1. 当前页面URL替换与跳转
    function handlePageRedirect() {
        let newUrl = location.href;
        for (const [oldKey, newKey] of Object.entries(redirect_url)) {
            if (newUrl.includes(oldKey)) {
                newUrl = newUrl.replace(oldKey, newKey);
                location.replace(newUrl);
                break;
            }
        }
    }

    // 2. 替换页面资源引用 [[5]]
    function replaceResourceUrls() {
        // 需要处理的标签属性
        const targets = [
            { selector: 'a', attr: 'href' },
            { selector: 'img', attr: 'src' },
            { selector: 'script', attr: 'src' },
            { selector: 'link', attr: 'href' }
        ];

        targets.forEach(target => {
            document.querySelectorAll(target.selector).forEach(el => {
                const attrValue = el.getAttribute(target.attr);
                if (attrValue) {
                    for (const [oldKey, newKey] of Object.entries(redirect_url)) {
                        if (attrValue.includes(oldKey)) {
                            el.setAttribute(
                                target.attr,
                                attrValue.replace(oldKey, newKey)
                            );
                            break;
                        }
                    }
                }
            });
        });
    }

    // 3. 屏蔽原生跳转(通过代理 a 标签点击事件)[[6]]
    function blockNativeRedirects() {
        document.addEventListener('click', (e) => {
            if (e.target.tagName === 'A') {
                const href = e.target.getAttribute('href');
                if (href && !href.startsWith('#')) {
                    e.preventDefault();
                    // 手动处理跳转
                    window.location.href = href;
                }
            }
        });
    }

    // 执行主流程
    handlePageRedirect();
    replaceResourceUrls();
    blockNativeRedirects();

    // 监听DOM变化处理动态内容 [[6]]
    const observer = new MutationObserver(() => {
        replaceResourceUrls();
    });

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

})();