Intoval/privateChatGPT
1
1// ==UserScript==2// @name Kelpy Codos3// @namespace https://github.com/Keldos-Li/Kelpy-Codos4// @version 1.0.55// @author Keldos; https://keldos.me/6// @description Add copy button to PRE tags before CODE tag, for Chuanhu ChatGPT especially. 7// Based on Chuanhu ChatGPT version: ac04408 (2023-3-22)8// @license GPL-3.09// @grant none10// ==/UserScript==11 12(function () {13 'use strict';14 15 function addCopyButton(pre) {16 var code = pre.querySelector('code');17 if (!code) {18 return; // 如果没有找到 <code> 元素,则不添加按钮19 }20 var firstChild = code.firstChild;21 if (!firstChild) {22 return; // 如果 <code> 元素没有子节点,则不添加按钮23 }24 var button = document.createElement('button');25 button.textContent = '\uD83D\uDCCE'; // 使用 📎 符号作为“复制”按钮的文本26 button.style.position = 'relative';27 button.style.float = 'right';28 button.style.fontSize = '1em'; // 可选:调整按钮大小29 button.style.background = 'none'; // 可选:去掉背景颜色30 button.style.border = 'none'; // 可选:去掉边框31 button.style.cursor = 'pointer'; // 可选:显示指针样式32 button.addEventListener('click', function () {33 var range = document.createRange();34 range.selectNodeContents(code);35 range.setStartBefore(firstChild); // 将范围设置为第一个子节点之前36 var selection = window.getSelection();37 selection.removeAllRanges();38 selection.addRange(range);39 40 try {41 var success = document.execCommand('copy');42 if (success) {43 button.textContent = '\u2714';44 setTimeout(function () {45 button.textContent = '\uD83D\uDCCE'; // 恢复按钮为“复制”46 }, 2000);47 } else {48 button.textContent = '\u2716';49 }50 } catch (e) {51 console.error(e);52 button.textContent = '\u2716';53 }54 55 selection.removeAllRanges();56 });57 code.insertBefore(button, firstChild); // 将按钮插入到第一个子元素之前58 }59 60 function handleNewElements(mutationsList, observer) {61 for (var mutation of mutationsList) {62 if (mutation.type === 'childList') {63 for (var node of mutation.addedNodes) {64 if (node.nodeName === 'PRE') {65 addCopyButton(node);66 }67 }68 }69 }70 }71 72 var observer = new MutationObserver(handleNewElements);73 observer.observe(document.documentElement, { childList: true, subtree: true });74 75 document.querySelectorAll('pre').forEach(addCopyButton);76})();77 