Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Created May 6, 2020 07:41
Show Gist options
  • Save n1ru4l/0a473bf845958a09ab72a7887535a470 to your computer and use it in GitHub Desktop.
Save n1ru4l/0a473bf845958a09ab72a7887535a470 to your computer and use it in GitHub Desktop.
Feature Detect AsyncClipboard API with TypeScript and provide it as a React hook
import * as React from "react";
interface ClipboardItem {
new (input: { [contentType: string]: Blob }): ClipboardItem;
}
type AsyncClipboardWriteFunction = (input: ClipboardItem) => Promise<void>;
declare global {
interface Window {
ClipboardItem: ClipboardItem | undefined;
}
interface Clipboard {
write?: AsyncClipboardWriteFunction;
}
}
interface AsyncClipboard extends Clipboard {
write: AsyncClipboardWriteFunction;
}
type ClipboardApi = {
clipboard: AsyncClipboard;
ClipboardItem: ClipboardItem;
};
export const getAsyncClipboardApi: () => ClipboardApi | null = () => {
if (
typeof window === "undefined" ||
typeof window.navigator.clipboard === "undefined" ||
typeof window.navigator.clipboard.write === "undefined" ||
typeof window.ClipboardItem === "undefined"
) {
return null;
}
return {
ClipboardItem: window.ClipboardItem,
clipboard: navigator.clipboard as AsyncClipboard,
};
};
export const useAsyncClipboardApi = () => {
const api = React.useMemo(() => getAsyncClipboardApi(), []);
return api;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment