Genspark Code Copy Button

为 Genspark.ai 代码区域添加复制按钮

  1. // ==UserScript==
  2. // @name Genspark Code Copy Button
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description 为 Genspark.ai 代码区域添加复制按钮
  6. // @author Your name
  7. // @match https://www.genspark.ai/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // 添加复制按钮的样式
  16. const style = document.createElement('style');
  17. style.textContent = `
  18. .code-copy-btn {
  19. position: absolute;
  20. right: 10px;
  21. top: 10px;
  22. padding: 4px 8px;
  23. background: #f0f0f0;
  24. border: 1px solid #ddd;
  25. border-radius: 4px;
  26. cursor: pointer;
  27. font-size: 12px;
  28. opacity: 0.8;
  29. transition: opacity 0.2s;
  30. z-index: 100;
  31. }
  32. .code-copy-btn:hover {
  33. opacity: 1;
  34. }
  35. .code-block-wrapper {
  36. position: relative;
  37. }
  38. `;
  39. document.head.appendChild(style);
  40.  
  41. // 监听 DOM 变化
  42. const observer = new MutationObserver((mutations) => {
  43. mutations.forEach((mutation) => {
  44. if (mutation.addedNodes.length) {
  45. addCopyButtons();
  46. }
  47. });
  48. });
  49.  
  50. observer.observe(document.body, {
  51. childList: true,
  52. subtree: true
  53. });
  54.  
  55. function addCopyButtons() {
  56. // 只选择代码区域内的代码块
  57. const codeBlocks = document.querySelectorAll('.hljs');
  58.  
  59. codeBlocks.forEach(codeBlock => {
  60. // 检查是否已经添加过按钮
  61. if (codeBlock.parentNode.querySelector('.code-copy-btn')) {
  62. return;
  63. }
  64.  
  65. // 为代码块添加包装器
  66. const wrapper = document.createElement('div');
  67. wrapper.className = 'code-block-wrapper';
  68. codeBlock.parentNode.insertBefore(wrapper, codeBlock);
  69. wrapper.appendChild(codeBlock);
  70.  
  71. // 创建复制按钮
  72. const copyButton = document.createElement('button');
  73. copyButton.className = 'code-copy-btn';
  74. copyButton.textContent = '复制';
  75. wrapper.appendChild(copyButton);
  76.  
  77. // 添加点击事件
  78. copyButton.addEventListener('click', async () => {
  79. try {
  80. await navigator.clipboard.writeText(codeBlock.textContent);
  81. copyButton.textContent = '已复制!';
  82. setTimeout(() => {
  83. copyButton.textContent = '复制';
  84. }, 2000);
  85. } catch (err) {
  86. console.error('复制失败:', err);
  87. copyButton.textContent = '复制失败';
  88. setTimeout(() => {
  89. copyButton.textContent = '复制';
  90. }, 2000);
  91. }
  92. });
  93. });
  94. }
  95.  
  96. // 初始执行一次
  97. addCopyButtons();
  98. })();