Copy Page as Markdown

Convert and copy the page content as Markdown to clipboard, excluding scripts and styles.

  1. // ==UserScript==
  2. // @name Copy Page as Markdown
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Convert and copy the page content as Markdown to clipboard, excluding scripts and styles.
  6. // @author You
  7. // @match *://*/*
  8. // @grant GM_setClipboard
  9. // @grant GM_addStyle
  10. // @require https://cdn.jsdelivr.net/npm/turndown@5.0.3/dist/turndown.js
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. // Remove <script> and <style> elements from the document
  18. function removeScriptsAndStyles(doc) {
  19. const elementsToRemove = doc.querySelectorAll('script, style');
  20. elementsToRemove.forEach(element => element.parentNode.removeChild(element));
  21. return doc;
  22. }
  23.  
  24. // Create a deep clone of the document body to work with, to preserve the original page content
  25. let clonedBody = document.body.cloneNode(true);
  26. clonedBody = removeScriptsAndStyles(clonedBody);
  27.  
  28. // Initialize Turndown service with the cloned body that excludes scripts and styles
  29. var turndownService = new TurndownService();
  30. var markdown = turndownService.turndown(clonedBody.innerHTML);
  31.  
  32. // Function to copy text to clipboard (might need permissions depending on the userscript manager)
  33. function copyTextToClipboard(text) {
  34. GM_setClipboard(text, 'text'); // Copy Markdown to clipboard
  35. }
  36.  
  37. // Add a button to trigger the conversion and copying
  38. var button = document.createElement('button');
  39. button.textContent = 'Copy as Markdown';
  40. button.style.position = 'fixed';
  41. button.style.top = '20px';
  42. button.style.right = '20px';
  43. button.style.zIndex = 10000;
  44. document.body.appendChild(button);
  45.  
  46. button.addEventListener('click', function() {
  47. copyTextToClipboard(markdown);
  48. });
  49. })();