强制后台打开所有链接

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

目前為 2025-02-03 提交的版本,檢視 最新版本

// ==UserScript==
// @name         强制后台打开所有链接
// @namespace    https://greasyfork.org/
// @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);

})();