Greasy Fork is available in English.
默认关闭,在当前站点启用后使所有普通链接在新标签打开
// ==UserScript==
// @license MIT
// @name 链接在新标签打开(可按站点启用)
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 默认关闭,在当前站点启用后使所有普通链接在新标签打开
// @author ChatGPT
// @match *://*/*
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.registerMenuCommand
// @run-at document-start
// ==/UserScript==
(async function() {
'use strict';
// 当前网站 host(不含协议)
const host = location.host;
// 从存储加载此域名是否启用
let enabled = await GM.getValue(host + "_openInNewTab", false);
// 注册 Tampermonkey 菜单项,点击切换开启/关闭
GM.registerMenuCommand(
`在 ${host} ${enabled ? "关闭" : "启用"} 新标签打开`,
async () => {
enabled = !enabled;
await GM.setValue(host + "_openInNewTab", enabled);
alert(`链接在新标签打开已 ${enabled ? "启用" : "关闭"} (${host})`);
}
);
// 若未启用则不处理
if (!enabled) return;
// 注入 link 处理逻辑
function handleLinks(target) {
// 遍历点击事件层(冒泡捕获)
target.addEventListener('click', function(event) {
const a = event.target.closest('a');
if (!a || !a.href) return;
// 如果本身已有 target 或右键/中键等则不干预
if (a.target || event.button !== 0) return;
// 设置新标签
a.target = "_blank";
}, true);
}
// 处理当前文档
handleLinks(document);
// 监听 DOM 动态改变(例如 SPA / 动态加载)
new MutationObserver((mutations) => {
mutations.forEach(() => {
handleLinks(document);
});
}).observe(document.documentElement, { childList: true, subtree: true });
})();