Greasy Fork is available in English.
新标签打开第三方链接,当前标签打开第一方链接。
当前为
// ==UserScript==
// @name 新标签打开第三方链接,当前标签打开第一方链接
// @version 1.2
// @author ChatGPT
// @description 新标签打开第三方链接,当前标签打开第一方链接。
// @match *://*/*
// @run-at document-end
// @namespace http://greasyfork.icu/users/452911
// ==/UserScript==
function openExternalLinksInNewTab() {
// 获取当前页面的主域名
var currentDomain = window.location.hostname;
// 选择页面上所有以'http'开头的超链接
var externalLinks = document.querySelectorAll('a[href^="http"]');
// 遍历这些超链接,仅对与当前页面不同域名的链接设置target属性为'_blank'
externalLinks.forEach(function(link) {
var linkDomain = new URL(link.href).hostname;
if (linkDomain !== currentDomain) {
link.setAttribute('target', '_blank');
}
});
// 选择页面上所有href属性以"/"开头的超链接
var internalLinks = document.querySelectorAll('a[href^="/"]');
// 遍历这些内部链接,将它们的target属性设置为"_self"
internalLinks.forEach(function(link) {
link.setAttribute('target', '_self');
});
}
// 执行函数
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);
})();