Greasy Fork

Greasy Fork is available in English.

新标签打开第三方链接

新标签打开第三方链接。

当前为 2024-03-20 提交的版本,查看 最新版本

// ==UserScript==
// @name         新标签打开第三方链接
// @version      1.0
// @author        ChatGPT
// @description  新标签打开第三方链接。
// @match        *://*/*
// @grant        GM_openInTab
// @namespace http://greasyfork.icu/users/452911
// ==/UserScript==

// 定义一个名为 openLinksInNewTab 的函数,并将现有代码放入其中
function openLinksInNewTab() {
    // 获取所有超链接元素
    var links = document.querySelectorAll("a[href^='http']:not(.linkProcessed)");

    // 遍历每个超链接
    for (var i = 0; i < links.length; i++) {
        var link = links[i];

        // 添加标记,表示已处理过
        link.classList.add("linkProcessed");

        // 添加点击事件监听器
        link.addEventListener("click", function(event) {
            // 获取链接的域名
            var domain = getDomainName(this.href);

            // 判断是否为第三方链接
            if (!isSameDomain(domain)) {
                // 取消默认行为,阻止超链接直接跳转
                event.preventDefault();

                // 在新标签页中打开链接
                GM_openInTab(this.href, { active: true });
            }
        });
    }

    // 判断给定的域名是否为当前网站的域名
    function isSameDomain(domain) {
        var currentDomain = getDomainName(window.location.href);
        return domain === currentDomain;
    }

    // 获取给定网址的域名
    function getDomainName(url) {
        var a = document.createElement("a");
        a.href = url;
        return a.hostname;
    }
}

// 调用 openLinksInNewTab 函数
openLinksInNewTab();

(function() {
    // 创建 MutationObserver 实例
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            // 迭代新增的节点
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                for (let i = 0; i < mutation.addedNodes.length; i++) {
                    const addedNode = mutation.addedNodes[i];
                    // 这里判断新增节点是否是元素节点,可以根据需要进行调整
                    if (addedNode.nodeType === Node.ELEMENT_NODE) {
                        // 在新增元素时执行
                        openLinksInNewTab();
                    }
                }
            }
        });
    });

    // 配置观察器
    const config = { childList: true, subtree: true };

    // 通过观察器实例与目标节点绑定
    observer.observe(document.body, config);
})();