Github链接新标签页打开

强制Github所有链接在新标签页打开

  1. // ==UserScript==
  2. // @name Github链接新标签页打开
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description 强制Github所有链接在新标签页打开
  6. // @author kang
  7. // @license MIT
  8. // @match *://github.com/*
  9. // @icon https://img.icons8.com/?size=128&id=HBaR-srJq-eB&format=png
  10. // @grant none
  11. // @run-at document-start
  12. // ==/UserScript==
  13.  
  14.  
  15. (function() {
  16. 'use strict';
  17.  
  18. // 增强型链接检测函数
  19. const findValidLink = (element) => {
  20. const MAX_DEPTH = 5; // 最大DOM层级搜索深度
  21. let current = element;
  22. let depth = 0;
  23.  
  24. while (current && depth++ < MAX_DEPTH) {
  25. if (current.tagName === 'A' && current.href) {
  26. // 排除伪链接和锚点
  27. if (current.href.includes('javascript:') ||
  28. current.href.startsWith('#')) return null;
  29. return current;
  30. }
  31. current = current.parentElement;
  32. }
  33. return null;
  34. };
  35.  
  36. // 主事件处理器
  37. const handleClick = (event) => {
  38. // 仅处理主按钮(左键)点击
  39. if (event.button !== 0) return;
  40.  
  41. // 保留辅助键功能(Ctrl/Cmd/Shift)
  42. if (event.ctrlKey || event.metaKey || event.shiftKey) return;
  43.  
  44. const link = findValidLink(event.target);
  45. if (!link) return;
  46.  
  47. // 阻止默认行为并停止传播
  48. event.preventDefault();
  49. event.stopImmediatePropagation();
  50.  
  51. // 异步打开新标签页(兼容SPA)
  52. setTimeout(() => {
  53. window.open(link.href, '_blank', 'noopener noreferrer');
  54. }, 50);
  55.  
  56. // 清除焦点状态
  57. link.blur();
  58. };
  59.  
  60. // 在捕获阶段优先注册(不可用)监听器
  61. document.addEventListener('click', handleClick, {
  62. capture: true,
  63. passive: false
  64. });
  65.  
  66. // 处理动态内容的重置防护
  67. let lastHref = location.href;
  68. const observeChanges = () => {
  69. if (location.href !== lastHref) {
  70. lastHref = location.href;
  71. document.addEventListener('click', handleClick, {
  72. capture: true,
  73. passive: false
  74. });
  75. }
  76. requestAnimationFrame(observeChanges);
  77. };
  78. observeChanges();
  79. })();

QingJ © 2025

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