Greasy Fork

Greasy Fork is available in English.

强制后台打开所有链接

所有链接强制后台新建标签页打开,兼容Firefox和Chrome

当前为 2025-02-03 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         强制后台打开所有链接
// @namespace    http://greasyfork.icu/
// @version      1.2
// @license      MIT
// @author       pugfly
// @match        *://*/*
// @grant        GM_openInTab
// @run-at       document-start
// @description 所有链接强制后台新建标签页打开,兼容Firefox和Chrome
// ==/UserScript==

(function() {
    'use strict';

    // ========== 核心逻辑 ==========

    // 1. 拦截所有链接点击
    function interceptLinkClicks(event) {
        let target = event.target;
        while (target && target.tagName !== 'A') {
            target = target.parentElement;
        }
        if (target && target.tagName === 'A' && target.href) {
            event.preventDefault();
            event.stopImmediatePropagation();
            GM_openInTab(target.href, { active: false });
            return false;
        }
    }
    document.addEventListener('click', interceptLinkClicks, true);
    document.addEventListener('auxclick', interceptLinkClicks, true);

    // 2. 通用搜索框处理
    function handleSearchForm(event) {
        const searchInput = document.querySelector('input[type="text"]');
        if (searchInput && (event.key === 'Enter' || event.type === 'submit')) {
            event.preventDefault();
            event.stopImmediatePropagation();
            const keyword = encodeURIComponent(searchInput.value.trim());
            if (keyword) {
                let searchUrl;
                if (window.location.hostname === 'www.bilibili.com') {
                    searchUrl = `https://search.bilibili.com/all?keyword=${keyword}`; // Bilibili 搜索 URL
                } else if (window.location.hostname === 'www.bing.com') {
                    searchUrl = `https://www.bing.com/search?q=${keyword}`; // Bing 搜索 URL
                } else {
                    searchUrl = `${document.location.origin}/search?q=${keyword}`; // 其他网站的通用搜索 URL
                }
                GM_openInTab(searchUrl, { active: false });
                return false;
            }
        }
    }

    // 监听搜索框的回车事件
    document.addEventListener('keydown', handleSearchForm, true);

    // 监听搜索框的提交事件
    document.addEventListener('submit', handleSearchForm, true);

})();