27 lines
858 B
TypeScript
27 lines
858 B
TypeScript
export interface ClipboardPayload {
|
|
files: File[];
|
|
text: string;
|
|
}
|
|
|
|
/** 读取剪贴板(需要用户手势与权限)。失败或被拒绝返回 null */
|
|
export async function readClipboard(): Promise<ClipboardPayload | null> {
|
|
try {
|
|
if (!navigator.clipboard.read) return { files: [], text: await navigator.clipboard.readText() };
|
|
const files: File[] = [];
|
|
let text = '';
|
|
for (const entry of await navigator.clipboard.read()) {
|
|
for (const type of entry.types) {
|
|
const blob = await entry.getType(type);
|
|
if (type.startsWith('image/')) {
|
|
files.push(new File([blob], `粘贴-${Date.now()}.${type.split('/')[1] ?? 'png'}`, { type }));
|
|
} else if (type === 'text/plain' && !text) {
|
|
text = await blob.text();
|
|
}
|
|
}
|
|
}
|
|
return { files, text };
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|