Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions package/src/components/page-toolbar-css/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import {
updateAnnotation as updateAnnotationOnServer,
deleteAnnotation as deleteAnnotationFromServer,
} from "../../utils/sync";
import { copyTextToClipboard } from "../../utils/clipboard";
import { getReactComponentName } from "../../utils/react-detection";
import {
getSourceLocation,
Expand Down Expand Up @@ -3107,11 +3108,7 @@ const [settings, setSettings] = useState<ToolbarSettings>(() => {
}

if (copyToClipboard) {
try {
await navigator.clipboard.writeText(output);
} catch {
// Clipboard may fail (permissions, not HTTPS, etc.) - continue anyway
}
await copyTextToClipboard(output);
}

// Fire callback with markdown output (always, regardless of clipboard success)
Expand Down
34 changes: 34 additions & 0 deletions package/src/utils/clipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* 将文本复制到剪贴板, 优先使用现代 Clipboard API,
* 在非安全上下文 (HTTP, 非 localhost) 下回退到 execCommand 方案.
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
// 优先使用 Clipboard API (需要安全上下文: HTTPS 或 localhost)
if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// 权限被拒绝或写入失败, 继续尝试回退方案
}
}

// 回退方案: 使用临时 textarea + execCommand('copy')
// 适用于非安全上下文 (HTTP) 或 Clipboard API 不可用的环境
try {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.top = "-9999px";
textarea.style.left = "-9999px";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
const succeeded = document.execCommand("copy");
document.body.removeChild(textarea);
return succeeded;
} catch {
return false;
}
}
1 change: 1 addition & 0 deletions package/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from "./element-identification";
export * from "./storage";
export * from "./source-location";
export * from "./sync";
export * from "./clipboard";