aboutsummaryrefslogtreecommitdiff
path: root/src/content/repositories/ClipboardRepository.ts
blob: a04685176e0ea849d175bde47070884021f514f8 (plain) (blame)
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
43
44
export default interface ClipboardRepository {
  read(): string;

  write(text: string): void;
}

export class ClipboardRepositoryImpl {
  read(): string {
    let textarea = window.document.createElement('textarea');
    window.document.body.append(textarea);

    textarea.style.position = 'fixed';
    textarea.style.top = '-100px';
    textarea.contentEditable = 'true';
    textarea.focus();

    let ok = window.document.execCommand('paste');
    let value = textarea.textContent!!;
    textarea.remove();

    if (!ok) {
      throw new Error('failed to access clipbaord');
    }

    return value;
  }

  write(text: string): void {
    let input = window.document.createElement('input');
    window.document.body.append(input);

    input.style.position = 'fixed';
    input.style.top = '-100px';
    input.value = text;
    input.select();

    let ok = window.document.execCommand('copy');
    input.remove();

    if (!ok) {
      throw new Error('failed to access clipbaord');
    }
  }
}