clipboard.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function canUseClipboardApi() {
  2. return (
  3. typeof navigator !== "undefined" &&
  4. Boolean(navigator.clipboard) &&
  5. typeof navigator.clipboard.writeText === "function"
  6. );
  7. }
  8. function copyWithExecCommand(text) {
  9. if (typeof document === "undefined") return false;
  10. if (typeof document.execCommand !== "function") return false;
  11. const textarea = document.createElement("textarea");
  12. textarea.value = String(text ?? "");
  13. textarea.setAttribute("readonly", "");
  14. textarea.style.position = "fixed";
  15. textarea.style.top = "-9999px";
  16. textarea.style.left = "-9999px";
  17. textarea.style.opacity = "0";
  18. document.body.appendChild(textarea);
  19. textarea.focus();
  20. textarea.select();
  21. textarea.setSelectionRange(0, textarea.value.length);
  22. let copied = false;
  23. try {
  24. copied = document.execCommand("copy");
  25. } catch {
  26. copied = false;
  27. } finally {
  28. textarea.remove();
  29. }
  30. return Boolean(copied);
  31. }
  32. export async function writeTextToClipboard(text) {
  33. const value = String(text ?? "");
  34. if (canUseClipboardApi()) {
  35. try {
  36. await navigator.clipboard.writeText(value);
  37. return { ok: true, method: "clipboard" };
  38. } catch {
  39. // Fall back to execCommand below.
  40. }
  41. }
  42. if (copyWithExecCommand(value)) {
  43. return { ok: true, method: "execCommand" };
  44. }
  45. return { ok: false, method: null };
  46. }