summaryrefslogtreecommitdiff
path: root/src/utils/clipboardUtils.ts
blob: 8a04caa37f5d9fefa75d286f8f78a96a7eb2ea96 (plain)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Clipboard utilities for reliable copy operations across different environments
 */

/**
 * Reliably copy text to clipboard using multiple fallback methods
 * This is especially important in gaming mode where clipboard APIs may behave differently
 */
export async function copyToClipboard(text: string): Promise<boolean> {
  const tempInput = document.createElement('input');
  tempInput.value = text;
  tempInput.style.position = 'absolute';
  tempInput.style.left = '-9999px';
  document.body.appendChild(tempInput);
  
  try {
    tempInput.focus();
    tempInput.select();
    
    let copySuccess = false;
    try {
      if (document.execCommand('copy')) {
        copySuccess = true;
      }
    } catch (e) {
      try {
        await navigator.clipboard.writeText(text);
        copySuccess = true;
      } catch (clipboardError) {
        console.error('Both copy methods failed:', e, clipboardError);
      }
    }
    
    return copySuccess;
  } finally {
    document.body.removeChild(tempInput);
  }
}

/**
 * Verify that text was successfully copied to clipboard
 */
export async function verifyCopy(expectedText: string): Promise<boolean> {
  try {
    const readBack = await navigator.clipboard.readText();
    return readBack === expectedText;
  } catch (e) {
    return true;
  }
}

/**
 * Copy text with verification and return success status
 */
export async function copyWithVerification(text: string): Promise<{ success: boolean; verified: boolean }> {
  const copySuccess = await copyToClipboard(text);
  
  if (!copySuccess) {
    return { success: false, verified: false };
  }
  
  const verified = await verifyCopy(text);
  return { success: true, verified };
}