Greasy Fork

强制所有链接在当前标签打开

强制所有链接在当前标签打开。

目前为 2022-06-25 提交的版本。查看 最新版本

// ==UserScript==
// @name         强制所有链接在当前标签打开
// @namespace    https://greasyfork.org/zh-CN/scripts/446917-%E5%BC%BA%E5%88%B6%E6%89%80%E6%9C%89%E9%93%BE%E6%8E%A5%E5%9C%A8%E5%BD%93%E5%89%8D%E6%A0%87%E7%AD%BE%E6%89%93%E5%BC%80
// @version      0.22
// @license MIT
// @description  强制所有链接在当前标签打开。
// @author       meteora
// @include *://*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';
    document.head.appendChild(document.createElement('base')).target = '_self';

    const listener=function (e){
        let dom = e.target
        if (dom.nodeName === 'A') {
            // e.stopPropagation() //阻止事件冒泡
            e.preventDefault() //阻止默认事件
            // dom.target = '_self'
            window.open(dom.href, '_self')
            return
        }
        //循环迭代获取父节点
        for (let i = 0; i < 5; i++) {
            dom = dom.parentNode
            //如果是a标签
            if (dom.nodeName === 'A') {
                // e.stopPropagation() //阻止事件冒泡
                e.preventDefault() //阻止默认事件
                // dom.target = '_self'
                window.open(dom.href, '_self')
                return;
            }
        }
        // if (e.target.nodeName === 'a') {
        //     console.log(e, 'event');
        //     // e.stopPropagation() //阻止事件冒泡
        //     // e.preventDefault() //阻止默认事件
        //     e.target.target = '_self';
        // }
    }

    document.body.addEventListener('click', listener,true)

    //对于调用window.open跳转的
    const open = window.open
    const newOpen = function (url = false, target = '_self', windowFeatures = false) {
        if (url && windowFeatures) {
            open(url, '_self', windowFeatures)
        } else if (url) {
            open(url, '_self')
        } else {
            open()
        }
    }
    Object.defineProperty(window, 'open', {
        value: newOpen
    })
})();