External Link Auto Redirect(Direct Link)

redirect to the real URL directly when clicking on a link that contains a redirect URL

当前为 2024-03-13 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name External Link Auto Redirect(Direct Link)
  3. // @name:zh-CN 外链自动重定向(默认直链)
  4. // @namespace http://tampermonkey.net/
  5. // @version 1.3
  6. // @description redirect to the real URL directly when clicking on a link that contains a redirect URL
  7. // @description:zh-CN 点击包含重定向 URL 的链接时,直接跳转到到真实的 URL
  8. // @author uiliugang
  9. // @run-at document-start
  10. // @match *://*/*
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. const redirectRegex = /^https?:\/\/.*\?.*https?/;
  18. const excludedExtensions = ['.m3u8', '.flv', '.ts'];
  19.  
  20. function processUrl(redirectURL) {
  21. // 登录页面,不做处理
  22. if (redirectURL.includes('login')) {
  23. return null;
  24. }
  25. const matches = redirectURL.match(redirectRegex);
  26. console.log(`Matches: ${matches}`);
  27. if (matches) {
  28. let index = redirectURL.substring(4).indexOf("http")+3;
  29. let realUrl = decodeURIComponent(redirectURL.substring(index + 1));
  30. //console.log(`Decoded URL: ${realUrl}`);
  31. if (isValidUrlAndNotExclude(realUrl)) {
  32. return realUrl;
  33. }
  34. }
  35. return null;
  36. }
  37.  
  38. function isValidUrlAndNotExclude(string) {
  39. try {
  40. const url = new URL(string);
  41. const pathname = url.pathname;
  42. for (const ext of excludedExtensions) {
  43. if (pathname.includes(ext)) {
  44. return false;
  45. }
  46. }
  47. return true;
  48. } catch (e) {
  49. return false;
  50. }
  51. }
  52.  
  53. document.addEventListener('click', function(e) {
  54. const element = e.target.closest('a[href]');
  55. if (element) {
  56. const processedUrl = processUrl(element.href);
  57. if (processedUrl) {
  58. e.preventDefault();
  59. window.open(processedUrl, '_blank');
  60. }
  61. }
  62. //console.log(`Original URL: ${element.href}`);
  63. //console.log(`Processed URL: ${processedUrl}`);
  64. });
  65.  
  66. let processedUrl = processUrl(window.location.href);
  67. if (processedUrl) {
  68. window.location.replace(processedUrl);
  69. }
  70. })();