Copy Text and HTML to Clipboard

library to copy the string and html parameters to the clipboard

当前为 2024-04-07 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/491896/1355860/Copy%20Text%20and%20HTML%20to%20Clipboard.js

  1. // ==UserScript==
  2. // @name Copy Text and HTML to Clipboard
  3. // @namespace https://greasyfork.org/en/users/906106-escctrl
  4. // @description library to copy the string and html parameters to the clipboard
  5. // @author escctrl
  6. // @version 1.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. function copy2Clipboard(e, str, html=null) {
  14. if (html === null) html = str;
  15. // trying first with the new Clipboard API
  16. try {
  17. const clipboardItem = new ClipboardItem({'text/html': new Blob([html], {type: 'text/html'}),
  18. 'text/plain': new Blob([str], {type: 'text/plain'})});
  19. navigator.clipboard.write([clipboardItem]);
  20. }
  21. // fallback method in case clipboard.write is not enabled - especially in Firefox it's disabled by default
  22. // to enable, go to about:config and turn dom.events.asyncClipboard.clipboardItem to true
  23. catch(err) {
  24. function listener(e) {
  25. e.clipboardData.setData("text/html", html);
  26. e.clipboardData.setData("text/plain", str);
  27. e.preventDefault();
  28. }
  29. document.addEventListener("copy", listener);
  30. document.execCommand("copy");
  31. document.removeEventListener("copy", listener);
  32. }
  33. }