Stack Overflow Copy Code

Add copy button to copy code inside Stack Overflow answers

2023-09-14 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name Stack Overflow Copy Code
  3. // @namespace https://t.me/OneFinalHug
  4. // @version 0.2
  5. // @license MIT
  6. // @description Add copy button to copy code inside Stack Overflow answers
  7. // @author OFH
  8. // @match https://stackoverflow.com/questions/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. function createCopyCodeButton() {
  16. const codeBlocks = document.querySelectorAll('pre code');
  17.  
  18. codeBlocks.forEach(codeBlock => {
  19. const codeContainer = codeBlock.parentNode;
  20. const copyButton = document.createElement('button');
  21. copyButton.textContent = 'Copy Code';
  22. copyButton.classList.add('copy-code-button');
  23.  
  24. copyButton.addEventListener('click', () => {
  25. const codeText = codeBlock.textContent;
  26. navigator.clipboard.writeText(codeText)
  27. .then(() => {
  28. copyButton.textContent = 'Copied!';
  29. setTimeout(() => {
  30. copyButton.textContent = 'Copy Code';
  31. }, 2000);
  32. })
  33. .catch(err => {
  34. console.error('Failed to copy code: ', err);
  35. });
  36. });
  37.  
  38. codeContainer.style.position = 'relative';
  39. copyButton.style.position = 'absolute';
  40. copyButton.style.top = '5px';
  41. copyButton.style.right = '5px';
  42.  
  43. codeContainer.appendChild(copyButton);
  44. });
  45. }
  46.  
  47. const customStyles = `
  48. .copy-code-button {
  49. background-color: #f2f2f2;
  50. border: none;
  51. border-color:red;
  52. border-radius: 3px;
  53. padding: 5px 10px;
  54. cursor: pointer;
  55. font-size: 12px;
  56. }
  57. .copy-code-button:hover {
  58. background-color: #ddd;
  59. }
  60. `;
  61.  
  62. const styleElement = document.createElement('style');
  63. styleElement.type = 'text/css';
  64. styleElement.appendChild(document.createTextNode(customStyles));
  65. document.head.appendChild(styleElement);
  66.  
  67. window.addEventListener('load', createCopyCodeButton);
  68. })();