谢谢 op, 使用中发现一个问题, 一些 pop 不需要跳转, 比如 v2 的感谢按钮, 所以更新了一版
// ==UserScript==
// @
name Force All Links to Open in New Tab
// @
namespace http://tampermonkey.net/// @
version 1.0
// @
description Make all links open in a new tab, while keeping the original page unchanged
// @
match *://*/*
// @
grant none
// @
license MIT
// ==/UserScript==
(function () {
'use strict';
function isPopupOrInteractiveLink(link) {
const url = link.href;
// Check if link has any event handlers (interactive functionality)
if (link.onclick || link.getAttribute('onclick') ||
link.getAttribute('onmousedown') || link.getAttribute('onmouseup')) {
return true;
}
// Check for data attributes that indicate JavaScript functionality
if (link.hasAttribute('data-toggle') || link.hasAttribute('data-target') ||
link.hasAttribute('data-dismiss') || link.hasAttribute('data-action') ||
link.hasAttribute('data-modal') || link.hasAttribute('data-popup')) {
return true;
}
// Check for CSS classes that typically indicate interactive elements
const interactiveClasses = ['modal-trigger', 'popup-trigger', 'lightbox-trigger',
'dialog-trigger', 'overlay-trigger', 'accordion-trigger',
'tab-trigger', 'dropdown-trigger', 'tooltip-trigger'];
if (interactiveClasses.some(cls => link.classList.contains(cls))) {
return true;
}
// Check for hash-only links that are used for JavaScript interactions
if (url.endsWith('#') || url.endsWith('#;') || url.includes('#!') ||
url === window.location.href + '#' || url === '#') {
return true;
}
// Check for javascript: URLs
if (url.startsWith('javascript:')) {
return true;
}
// Check for void(0) patterns
if (/void\(0\)/i.test(url)) {
return true;
}
// Check for same-page anchors (internal page navigation)
if (url.includes('#') && url.split('#')[0] === window.location.href.split('#')[0]) {
return true;
}
// Common popup URL patterns
const popupPatterns = [
/popup/i, /modal/i, /overlay/i, /lightbox/i, /dialog/i, /window\.open/i,
/fancybox/i, /colorbox/i, /thickbox/i, /magnific/i, /photoswipe/i,
/gallery/i, /slideshow/i, /carousel/i, /accordion/i, /tabs?/i,
/dropdown/i, /tooltip/i, /share/i, /social/i
];
return popupPatterns.some(pattern => pattern.test(url));
}
function openInNewTab(event) {
const link = event.target.closest('a'); // Find the clicked link
if (link && link.href && !link.hasAttribute('target')) {
// Check if this is a popup or interactive link
if (isPopupOrInteractiveLink(link)) {
// Let popup/interactive links behave normally (don't interfere)
return;
}
event.preventDefault(); // Block the default behavior
event.stopPropagation(); // Prevent bubbling so internal JS won't trigger navigation
setTimeout(() => {
window.open(link.href, '_blank'); // Open link in a new tab
}, 50); // Small delay for compatibility
}
}
// Attach the click listener to the whole document
document.addEventListener('click', openInNewTab, true);
})();