Skip to content

Commit 2817600

Browse files
Improve clipboard copy with error handling and fallback mechanism
Co-authored-by: rahul.chhabria <[email protected]>
1 parent af2e61d commit 2817600

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/components/copyForLLMButton.tsx

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
'use client';
22

33
import {useState} from 'react';
4-
import {Check, Clipboard} from 'react-feather';
4+
import {Check,Clipboard} from 'react-feather';
55
import * as Sentry from '@sentry/nextjs';
66

7+
async function tryWriteClipboard(text: string): Promise<boolean> {
8+
try {
9+
if (navigator?.clipboard) {
10+
await navigator.clipboard.writeText(text);
11+
return true;
12+
}
13+
} catch (err) {
14+
Sentry.captureException(err);
15+
}
16+
return false;
17+
}
18+
719
interface Props {
820
/** Absolute path to the markdown version of this page (e.g. `/docs/page.md`) */
921
markdownPath: string;
@@ -20,8 +32,7 @@ export function CopyForLLMButton({markdownPath}: Props) {
2032
const response = await fetch(markdownPath);
2133
if (response.ok) {
2234
const text = await response.text();
23-
await navigator.clipboard.writeText(text);
24-
didCopy = true;
35+
didCopy = await tryWriteClipboard(text);
2536
}
2637
} catch (err) {
2738
// network error handled below in fallback
@@ -31,8 +42,7 @@ export function CopyForLLMButton({markdownPath}: Props) {
3142
// Fallback: copy the markdown URL if first attempt failed
3243
if (!didCopy) {
3344
try {
34-
await navigator.clipboard.writeText(window.location.origin + markdownPath);
35-
didCopy = true;
45+
didCopy = await tryWriteClipboard(window.location.origin + markdownPath);
3646
} catch (err) {
3747
Sentry.captureException(err);
3848
}

0 commit comments

Comments
 (0)