LeetCode 跳转到 LeetCode.cn

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

目前為 2024-04-10 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         LeetCode 跳转到 LeetCode.cn
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  在 LeetCode.com 上添加一个跳转到 LeetCode.cn 的超链接按钮
// @author       Moranjianghe
// @match        https://leetcode.com/*
// @license      MIT
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 创建一个新的<a>元素作为按钮
    var link = document.createElement('a');
    var buttonText = document.createTextNode('跳转到 LeetCode.cn');
    link.appendChild(buttonText);
    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';

    // 设置超链接的 href 属性
    function updateLink() {
        var path = window.location.pathname;
        var newUrl = 'https://leetcode.cn' + path;
        link.setAttribute('href', newUrl);
    }

    // 使用 MutationObserver 监听 URL 变化
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList') {
                updateLink(); // 当 URL 变化时更新超链接
            }
        });
    });

    var config = { childList: true, subtree: true };
    observer.observe(document.body, config); // 开始监听

    // 尝试添加按钮到目标<div>
    function tryAppendButton() {
        var targetDiv = document.getElementById('ide-top-btns');
        if (targetDiv) {
            targetDiv.appendChild(link);
            clearInterval(appendButtonInterval); // 如果找到目标元素,停止尝试
        }
    }

    var appendButtonInterval = setInterval(tryAppendButton, 500); // 每500毫秒尝试一次添加按钮
})();