Force Link Open in New

Opens all web links in new tabs, enhancing browsing efficiency and preventing loss of work progress.

目前為 2024-06-26 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Force Link Open in New
// @name:zh-CN      强制链接在新页打开
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Opens all web links in new tabs, enhancing browsing efficiency and preventing loss of work progress.
// @description:zh-CN  让所有网页链接都在新标签页中打开,提升浏览效率。
// @author       Yearly
// @license      AGPL-v3.0
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Capture all click events and open links in a new tab
    document.addEventListener('click', function(event) {
        let anchor = event.target.closest('a');
        if (anchor && anchor.href) {
            event.preventDefault();
            window.open(anchor.href, '_blank');
        }
    }, true);

    // Capture all form submit events and open the form's action URL in a new tab
    document.addEventListener('submit', function(event) {
        event.preventDefault();
        let form = event.target;
        if (form && form.action) {
            window.open(form.action, '_blank');
        }
    }, true);

    // Override window.open method to open URLs in a new tab
    const originalOpen = window.open;
    window.open = function(url, target = '_blank', features) {
        if (['_self', '_parent', '_top'].includes(target)) {
            target = '_blank';
        }
        return originalOpen.call(window, url, target, features);
    };

    // Proxy for window.location to intercept direct assignments to href
    const locationProxy = new Proxy(window.location, {
        set(target, property, value) {
            if (property === 'href') {
                window.open(value, '_blank');
                return true;
            }
            target[property] = value;
            return true;
        }
    });

    // Prevent page reload by listening to beforeunload event
    window.addEventListener('beforeunload', function(event) {
        const newUrl = window.location.href;
        window.open(newUrl, '_blank');
        event.preventDefault();
        event.returnValue = ''; // Compatibility for some browsers
    });

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址