File size: 1,134 Bytes
cf47645
 
 
 
 
 
 
 
 
 
 
 
9104321
cf47645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Copies a string to the clipboard, with a fallback for older browsers.
 *
 * @param text The string to copy to the clipboard.
 * @returns A promise that resolves when the text has been successfully copied,
 *          or rejects if the copy operation fails.
 */
export async function copyToClipboard(text: string): Promise<void> {
	if (navigator.clipboard) {
		try {
			await navigator.clipboard.writeText(text);
			return; // Resolve immediately if successful
		} catch {
			// Fallback to the older method
		}
	}

	// Fallback for browsers that don't support the Clipboard API
	try {
		const textArea = document.createElement("textarea");
		textArea.value = text;

		// Avoid scrolling to bottom of page in MS Edge.
		textArea.style.top = "0";
		textArea.style.left = "0";
		textArea.style.position = "fixed";

		document.body.appendChild(textArea);
		textArea.focus();
		textArea.select();

		const successful = document.execCommand("copy");
		document.body.removeChild(textArea);

		if (!successful) {
			throw new Error("Failed to copy text using fallback method.");
		}
	} catch (err) {
		return Promise.reject(err);
	}
}