LeetCode 跳转到 LeetCode.cn

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

As of 2024-04-10. See the latest version.

  1. // ==UserScript==
  2. // @name LeetCode 跳转到 LeetCode.cn
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  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 = 'relative flex overflow-hidden rounded bg-fill-tertiary dark:bg-fill-tertiary ml-[6px]';
  20. link.style.paddingLeft = '8px'
  21. link.style.paddingRight = '8px'
  22. link.style.textAlign = 'center';
  23.  
  24. // 设置超链接的 href 属性
  25. function updateLink() {
  26. var path = window.location.pathname;
  27. var newUrl = 'https://leetcode.cn' + path;
  28. link.setAttribute('href', newUrl);
  29. }
  30.  
  31. // 使用 MutationObserver 监听 URL 变化
  32. var observer = new MutationObserver(function(mutations) {
  33. mutations.forEach(function(mutation) {
  34. if (mutation.type === 'childList') {
  35. updateLink(); // 当 URL 变化时更新超链接
  36. }
  37. });
  38. });
  39.  
  40. var config = { childList: true, subtree: true };
  41. observer.observe(document.body, config); // 开始监听
  42.  
  43. // 尝试添加按钮到目标<div>
  44. function tryAppendButton() {
  45. var targetDiv = document.getElementById('ide-top-btns');
  46. if (targetDiv) {
  47. targetDiv.appendChild(link);
  48. clearInterval(appendButtonInterval); // 如果找到目标元素,停止尝试
  49. }
  50. }
  51.  
  52. var appendButtonInterval = setInterval(tryAppendButton, 500); // 每500毫秒尝试一次添加按钮
  53. })();