在 LeetCode 問題頁面上,按下按鈕後擷取問題描述內容。
当前为
- // ==UserScript==
- // @name LeetCode 問題描述內容擷取器
- // @namespace https://your.namespace/
- // @version 1.1
- // @description 在 LeetCode 問題頁面上,按下按鈕後擷取問題描述內容。
- // @author abc0922001
- // @match https://leetcode.com/problems/*
- // @grant none
- // @license MIT
- // ==/UserScript==
- (function () {
- 'use strict';
- // 等待指定選取器元素出現
- function waitForElement(selector, timeout = 5000) {
- return new Promise((resolve, reject) => {
- const el = document.querySelector(selector);
- if (el) {
- return resolve(el);
- }
- const observer = new MutationObserver((mutations, obs) => {
- const el = document.querySelector(selector);
- if (el) {
- obs.disconnect();
- resolve(el);
- }
- });
- observer.observe(document.body, { childList: true, subtree: true });
- setTimeout(() => {
- observer.disconnect();
- reject(new Error('Timeout'));
- }, timeout);
- });
- }
- // 建立一個按鈕
- const btn = document.createElement('button');
- btn.textContent = '擷取描述';
- btn.style.position = 'fixed';
- btn.style.top = '10px';
- btn.style.right = '10px';
- btn.style.zIndex = 1000;
- document.body.appendChild(btn);
- btn.addEventListener('click', () => {
- // 根據提供的 HTML,等待目標元素出現
- waitForElement('div.elfjS[data-track-load="description_content"]', 5000)
- .then(targetDiv => {
- const htmlContent = targetDiv.innerHTML;
- // 在頁面上建立一個 textarea 來顯示擷取的內容
- const textarea = document.createElement('textarea');
- textarea.style.position = 'fixed';
- textarea.style.top = '50px';
- textarea.style.right = '10px';
- textarea.style.width = '300px';
- textarea.style.height = '300px';
- textarea.value = htmlContent;
- document.body.appendChild(textarea);
- console.log(htmlContent);
- })
- .catch(err => {
- alert('找不到目標內容');
- console.error(err);
- });
- });
- })();