新标签打开第三方链接,当前标签打开第一方链接

新标签打开第三方链接,当前标签打开第一方链接。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         新标签打开第三方链接,当前标签打开第一方链接
// @version      1.3
// @author       ChatGPT
// @description  新标签打开第三方链接,当前标签打开第一方链接。
// @match        *://*/*
// @run-at       document-end
// @namespace    https://greasyfork.org/users/452911
// ==/UserScript==

function handleLinks() {
    const currentDomain = window.location.hostname;

    // 处理外部链接
    document.querySelectorAll('a').forEach(link => {
        if (link.href.startsWith("http") && new URL(link.href).hostname !== currentDomain) {
            link.setAttribute('target', '_blank');
        } else {
            link.setAttribute('target', '_self');
        }
    });

    // 处理内部链接
    document.querySelectorAll('a[href^="/"]').forEach(link => {
        link.setAttribute('target', '_self');
    });
}

// 执行函数
handleLinks();

(function() {
    const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.addedNodes.length > 0) {
                mutation.addedNodes.forEach(addedNode => {
                    if (addedNode.nodeType === Node.ELEMENT_NODE) {
                        handleLinks();
                    }
                });
            }
        });
    });

    const config = { childList: true, subtree: true };

    observer.observe(document.body, config);
})();