Copy Text and HTML to Clipboard

library to copy plain and html MIME types to the clipboard

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/491896/1516188/Copy%20Text%20and%20HTML%20to%20Clipboard.js

  1. // ==UserScript==
  2. // @name Copy Text and HTML to Clipboard
  3. // @namespace https://gf.qytechs.cn/en/users/906106-escctrl
  4. // @description library to copy plain and html MIME types to the clipboard
  5. // @author escctrl
  6. // @version 2.0
  7. // @grant none
  8. // @license MIT
  9. // ==/UserScript==
  10.  
  11. // solution for setting richtext clipboard content found at https://jsfiddle.net/jdhenckel/km7prgv4/3/
  12. // and https://stackoverflow.com/questions/34191780/javascript-copy-string-to-clipboard-as-text-html/74216984#74216984
  13.  
  14. /* different modes for copying:
  15. * txt = only plaintext = when a text or url should never be formatted, even if the target supports richtext
  16. * fmt = visible HTML (MIME are same) = when richtext programs should paste formatted text (chat), and plaintext fields should paste the HTML (Ao3 comments)
  17. * invisible HTML (MIME differ) = when richtext programs should paste formatted text, but if the program doesn't support it (e.g. Notepad), copy some other plain text (no HTML visible)
  18. */
  19.  
  20. function copy2Clipboard(e, mode, plain, html=null) {
  21. if (!plain) { // stop if null, undefined, or "". we always expect plaintext content as a minimum
  22. console.log('Copying to Clipboard failed: no text was given to copy');
  23. return;
  24. }
  25. // if no separate html content is given but html MIME is supposed to be filled, we reuse the plain content
  26. if (mode === "fmt" && !html) html = plain;
  27. // trying first with the new Clipboard API
  28. try {
  29. let clipboardItem;
  30. // 'only plaintext' mode does not provide the text/html MIME type so it can't be used by richtext programs
  31. if (mode === "txt") clipboardItem = new ClipboardItem({ 'text/plain': new Blob([plain], {type: 'text/plain'}) });
  32. else clipboardItem = new ClipboardItem({ 'text/html': new Blob([html], {type: 'text/html'}),
  33. 'text/plain': new Blob([plain], {type: 'text/plain'}) });
  34. navigator.clipboard.write([clipboardItem]);
  35. }
  36. // fallback method in case clipboard.write is not enabled - especially in Firefox it's disabled by default
  37. // to enable, go to about:config and turn dom.events.asyncClipboard.clipboardItem to true
  38. catch(err) {
  39. function listener(e) {
  40. e.clipboardData.setData("text/plain", plain);
  41. if (mode === "fmt") e.clipboardData.setData("text/html", html);
  42. e.preventDefault();
  43. }
  44. document.addEventListener("copy", listener);
  45. document.execCommand("copy");
  46. document.removeEventListener("copy", listener);
  47. }
  48. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址