| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- function canUseClipboardApi() {
- return (
- typeof navigator !== "undefined" &&
- Boolean(navigator.clipboard) &&
- typeof navigator.clipboard.writeText === "function"
- );
- }
- function copyWithExecCommand(text) {
- if (typeof document === "undefined") return false;
- if (typeof document.execCommand !== "function") return false;
- const textarea = document.createElement("textarea");
- textarea.value = String(text ?? "");
- textarea.setAttribute("readonly", "");
- textarea.style.position = "fixed";
- textarea.style.top = "-9999px";
- textarea.style.left = "-9999px";
- textarea.style.opacity = "0";
- document.body.appendChild(textarea);
- textarea.focus();
- textarea.select();
- textarea.setSelectionRange(0, textarea.value.length);
- let copied = false;
- try {
- copied = document.execCommand("copy");
- } catch {
- copied = false;
- } finally {
- textarea.remove();
- }
- return Boolean(copied);
- }
- export async function writeTextToClipboard(text) {
- const value = String(text ?? "");
- if (canUseClipboardApi()) {
- try {
- await navigator.clipboard.writeText(value);
- return { ok: true, method: "clipboard" };
- } catch {
- // Fall back to execCommand below.
- }
- }
- if (copyWithExecCommand(value)) {
- return { ok: true, method: "execCommand" };
- }
- return { ok: false, method: null };
- }
|