Copy Last Code Block on ChatGPT Without Header

Adds a button to copy the last code block on chat.openai.com without copying the header

  1. // ==UserScript==
  2. // @name Copy Last Code Block on ChatGPT Without Header
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.2
  5. // @description Adds a button to copy the last code block on chat.openai.com without copying the header
  6. // @author max5555
  7. // @license MIT
  8. // @match https://chat.openai.com/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Create the copy button
  16. const copyButton = document.createElement('button');
  17. copyButton.textContent = 'Copy Last Code';
  18. copyButton.style.position = 'fixed';
  19. copyButton.style.bottom = '20px';
  20. copyButton.style.right = '20px';
  21. copyButton.style.zIndex = '1000';
  22.  
  23. // Add the button to the body
  24. document.body.appendChild(copyButton);
  25.  
  26. // Function to show notification
  27. function showNotification(message, duration = 3000) {
  28. const notification = document.createElement('div');
  29. notification.textContent = message;
  30. notification.style.position = 'fixed';
  31. notification.style.bottom = '50px';
  32. notification.style.right = '20px';
  33. notification.style.backgroundColor = 'lightgreen';
  34. notification.style.padding = '10px';
  35. notification.style.borderRadius = '5px';
  36. notification.style.boxShadow = '0 0 5px rgba(0, 0, 0, 0.3)';
  37. notification.style.zIndex = '1001';
  38.  
  39. document.body.appendChild(notification);
  40.  
  41. setTimeout(() => {
  42. notification.remove();
  43. }, duration);
  44. }
  45.  
  46. // Function to copy the last code block
  47. copyButton.addEventListener('click', () => {
  48. const codeContainers = document.querySelectorAll('pre code');
  49. if (codeContainers.length > 0) {
  50. const lastCodeContainer = codeContainers[codeContainers.length - 1];
  51. navigator.clipboard.writeText(lastCodeContainer.textContent).then(() => {
  52. showNotification('Code copied to clipboard!');
  53. }).catch(err => {
  54. console.error('Failed to copy text: ', err);
  55. });
  56. } else {
  57. showNotification('No code blocks found!');
  58. }
  59. });
  60. })();