Skip to content

copyToClipboard()

copyToClipboard(text, callback?, timeout?): Promise<boolean>

Defined in: src/utils/domUtils.ts:66

Copies the given text to the clipboard.

This function uses the Clipboard API to copy the specified text to the clipboard. It supports an optional callback function that is executed immediately after the text is copied, and optionally executed again after a specified timeout.

Parameters

text

string

The text to copy to the clipboard.

callback?

() => void

An optional callback to run after the text is copied.

timeout?

number

Optional timeout in milliseconds to trigger the callback again after the delay.

Returns

Promise<boolean>

A promise that resolves to true if the copy was successful, or false otherwise.

Examples

tsx
copyToClipboard('Hello, world!', () => {
  console.log('Text copied!');
});
tsx
const success = await copyToClipboard('Hello, world!');
console.log(success ? 'Copied!' : 'Failed to copy!');
tsx
copyToClipboard('Hello, world!', () => {
  console.log('Callback triggered!');
}, 2000);
// Immediately logs "Callback triggered!" and logs it again after 2 seconds.

Released under the MIT License.