Greasy Fork is available in English.

LeetCode 跳转到 LeetCode.cn

在 LeetCode.com 上添加一个跳转到 LeetCode.cn 的超链接按钮

  1. // ==UserScript==
  2. // @name LeetCode 跳转到 LeetCode.cn
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description 在 LeetCode.com 上添加一个跳转到 LeetCode.cn 的超链接按钮
  6. // @author Moranjianghe
  7. // @match https://leetcode.com/*
  8. // @license MIT
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // 创建一个新的<a>元素作为按钮
  16. var link = document.createElement('a');
  17. var buttonText = document.createTextNode('跳转到 LeetCode.cn');
  18. link.appendChild(buttonText);
  19. link.className = 'ml-2 group/nav-back cursor-pointer gap-2 hover:text-lc-icon-primary dark:hover:text-dark-lc-icon-primary flex items-center h-[32px] transition-none hover:bg-fill-quaternary dark:hover:bg-fill-quaternary text-gray-60 dark:text-gray-60 px-2';
  20.  
  21. // 设置超链接的 href 属性
  22. function updateLink() {
  23. var path = window.location.pathname;
  24. var newUrl = 'https://leetcode.cn' + path;
  25. link.setAttribute('href', newUrl);
  26. }
  27.  
  28. // 使用 MutationObserver 监听 URL 变化
  29. var observer = new MutationObserver(function(mutations) {
  30. mutations.forEach(function(mutation) {
  31. if (mutation.type === 'childList') {
  32. updateLink(); // 当 URL 变化时更新超链接
  33. }
  34. });
  35. });
  36.  
  37. var config = { childList: true, subtree: true };
  38. observer.observe(document.body, config); // 开始监听
  39.  
  40. // 尝试添加按钮到目标<div>
  41. function tryAppendButton() {
  42. var targetDiv = document.getElementById('ide-top-btns');
  43. if (targetDiv) {
  44. targetDiv.appendChild(link);
  45. clearInterval(appendButtonInterval); // 如果找到目标元素,停止尝试
  46. }
  47. }
  48.  
  49. var appendButtonInterval = setInterval(tryAppendButton, 500); // 每500毫秒尝试一次添加按钮
  50. })();