自动重定向

替换重定向的链接

目前为 2023-01-30 提交的版本。查看 最新版本

// ==UserScript==
// @name         自动重定向
// @namespace    http://tampermonkey.net/
// @version      0.1.0
// @description  替换重定向的链接
// @author       share121
// @match        *://*/*
// @grant        none
// @run-at       document-start
// @license      MIT
// ==/UserScript==

(() => {
    function changHref(ele) {
        try {
            if (ele.href) {
                fetch(new URL(ele.href, location.href).toString(), {
                    method: "HEAD",
                })
                    .then((e) => {
                        if (e.url && e.url !== ele.href) {
                            ele.href = e.url;
                        }
                    })
                    .catch((e) => console.error(e));
            }
        } catch (e) {
            console.error(e);
        }
    }
    new MutationObserver((mutationList) => {
        mutationList.forEach((e) => {
            if (e.type === "attributes") {
                if (e.target instanceof HTMLAnchorElement) {
                    changHref(e.target);
                }
            } else {
                e.addedNodes.forEach((ele) => {
                    if (ele instanceof HTMLAnchorElement) {
                        changHref(ele);
                    }
                });
            }
        });
    }).observe(document, {
        subtree: true,
        childList: true,
        attributeFilter: ["href"],
    });
    window.addEventListener("mouseover", (e) => {
        if (e.target instanceof HTMLAnchorElement) {
            changHref(e.target);
        }
    });
})();