-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclipboard.ts
42 lines (37 loc) · 1.24 KB
/
clipboard.ts
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
interface ClipboardDataInterface {
setData(format: string, data: string): boolean;
}
declare global {
interface Window {
clipboardData: ClipboardDataInterface;
}
}
function copyToClipboardWithAlert(text: string) {
if (!clipboard(text)) {
alert('failed to copy to clipboard');
}
}
export function elToClipboard(e: React.MouseEvent<HTMLElement>) {
copyToClipboardWithAlert(e.currentTarget.dataset.toClipboard!);
}
// thanks https://stackoverflow.com/a/33928558
export default function clipboard(text: string): boolean {
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return window.clipboardData.setData('Text', text);
} else if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
const textarea = document.createElement('textarea');
textarea.textContent = text;
textarea.style.position = 'fixed'; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand('copy'); // Security exception may be thrown by some browsers.
} catch (ex) {
return false;
} finally {
document.body.removeChild(textarea);
}
}
return false;
}