-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-text.ts
More file actions
42 lines (39 loc) · 1.1 KB
/
Copy pathcopy-text.ts
File metadata and controls
42 lines (39 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
export type CopyDocument = {
readonly body: HTMLElement;
readonly createElement: (tagName: "textarea") => HTMLTextAreaElement;
readonly execCommand?: (command: string) => boolean;
};
type CopyTextOptions = {
readonly clipboard?: Pick<Clipboard, "writeText">;
readonly document?: CopyDocument;
};
export async function copyText(
text: string,
options: CopyTextOptions = {},
): Promise<boolean> {
if (options.clipboard) {
try {
await options.clipboard.writeText(text);
return true;
} catch {
// Continue to the synchronous fallback supported by older WebViews.
}
}
const target = options.document ?? document;
const textarea = target.createElement("textarea") as HTMLTextAreaElement;
textarea.value = text;
textarea.readOnly = true;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
target.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
try {
return target.execCommand?.("copy") === true;
} catch {
return false;
} finally {
textarea.remove();
}
}