// ==UserScript== // @name 新标签打开第三方链接 // @version 1.1 // @author ChatGPT // @description 新标签打开第三方链接。 // @match *://*/* // @run-at document-end // @namespace https://greasyfork.org/users/452911 // @downloadURL none // ==/UserScript== function openExternalLinksInNewTab() { // 获取当前页面的主域名 var currentDomain = window.location.hostname; // 选择页面上所有以'http'或'https'开头的超链接 var externalLinks = document.querySelectorAll('a[href^="http"], a[href^="https"]'); // 遍历这些超链接,仅对与当前页面不同域名的链接设置target属性为'_blank' externalLinks.forEach(function(link) { var linkDomain = new URL(link.href).hostname; if (linkDomain !== currentDomain) { link.setAttribute('target', '_blank'); } }); } // 执行函数 openExternalLinksInNewTab(); (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) { // 在新增元素时执行 openExternalLinksInNewTab(); } } } }); }); // 配置观察器 const config = { childList: true, subtree: true }; // 通过观察器实例与目标节点绑定 observer.observe(document.body, config); })();