CSDNCodeCopier

Down with CSDN paywall. Adds buttons for copying content from code snippets in CSDN blog posts

  1. // ==UserScript==
  2. // @name CSDNCodeCopier
  3. // @namespace https://blog.csdn.net/
  4. // @version 1.0
  5. // @description Down with CSDN paywall. Adds buttons for copying content from code snippets in CSDN blog posts
  6. // @author aisuneko
  7. // @match *://blog.csdn.net/*/article/details/*
  8. // @match *://*.blog.csdn.net/article/details/*
  9. // @grant none
  10. // ==/UserScript==
  11. async function copyToClipboard(text){
  12. try {
  13. await navigator.clipboard.writeText(text);
  14. } catch (error) {
  15. console.error(error.message);
  16. }
  17. }
  18.  
  19. function unescapeHTML(html) {
  20. return html.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
  21. }
  22.  
  23. (function() {
  24. 'use strict';
  25. let taglist = ["set-code-show", "set-code-hide"];
  26. let snippetlist = [];
  27. taglist.forEach((tag)=>{
  28. let tmparr = Array.from(document.getElementsByClassName(tag));
  29. snippetlist.push(...tmparr);
  30. });
  31. for(let i of snippetlist){
  32. let button = document.createElement("button");
  33. button.textContent = "Copy Code";
  34. let code = i.getElementsByTagName("code")[0].innerHTML.toString().replaceAll(/<[^>]*>/gi,"");
  35. button.addEventListener("click", () => {
  36. copyToClipboard(unescapeHTML(code));
  37. button.textContent = "Copied!";
  38. });
  39. i.appendChild(button);
  40. }
  41. Array.from(document.getElementsByClassName("hljs-button signin active")).forEach((el)=>{el.remove()});
  42. })();