Stack Overflow Code Copy

Adds a small copy button to the top right corner of all code blocks on Stack Overflow making the copying process a breeze

目前为 2024-06-01 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Stack Overflow Code Copy
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.1
  5. // @description Adds a small copy button to the top right corner of all code blocks on Stack Overflow making the copying process a breeze
  6. // @match https://stackoverflow.com/questions/*
  7. // @grant none
  8. // @license MIT
  9. // ==/UserScript==
  10.  
  11. /*
  12. Update Notes:
  13. v1.1 - Adjusted button positioning to ensure it stays at the top right corner of the code box, even with horizontal scrolling due to long lines of code.
  14. v1.0 - Initial release which added a copy button to code blocks.
  15. */
  16.  
  17. (function() {
  18. 'use strict';
  19.  
  20. function addCopyButton(codeBlock) {
  21. const button = document.createElement('button');
  22. button.innerHTML = 'Copy';
  23. button.style.position = 'absolute';
  24. button.style.top = '5px';
  25. button.style.right = '5px';
  26. button.style.zIndex = '10'; // Ensure the button stays on top
  27. button.onclick = function() {
  28. const code = codeBlock.querySelector('code').innerText;
  29. navigator.clipboard.writeText(code);
  30. };
  31. const wrapper = document.createElement('div');
  32. wrapper.style.position = 'relative';
  33. codeBlock.style.position = 'relative';
  34. wrapper.appendChild(codeBlock.cloneNode(true));
  35. codeBlock.parentNode.replaceChild(wrapper, codeBlock);
  36. wrapper.appendChild(button);
  37. }
  38.  
  39. const codeBlocks = document.querySelectorAll('pre');
  40. codeBlocks.forEach(addCopyButton);
  41. })();