getClipboardText

Category Browser

Provides write (and optionally read) access to the text clipboard.

Demo

Your browser doesn't support the Clipboard API...

Usage

Set options.legacyCopy: true to keep the ability to copy if the Clipboard API is not available. It will handle copy with document.execCommand as the fallback.

<script>
	import { getClipboardText } from '@sv-use/core';
 
	const clipboard = getClipboardText({
        allowRead: true,
        legacyCopy: true
    });
</script>

Examples

<script>
	import { getClipboardText } from '@sv-use/core';
 
	let inputValue = $state('');
	const clipboard = getClipboardText({
        allowRead: true,
        legacyCopy: true
    });
</script>
 
<div>
    <span>Currently copied : {clipboard.text}</span>
    <input type="text" bind:value={inputValue} />
    <button onclick={() => clipboard.copyText(inputValue)}>
        Copy text from input
    </button>
</div>
Type definitions
import type { CleanupFunction } from '../../__internal__/types.js';
type GetClipboardOptions<AllowRead extends boolean> = {
    /**
     * Whether to automatically clean up the event listeners or not.
     * @note If set to `true`, you must call `getClipboardText` in the component initialization lifecycle.
     * @default true
     */
    autoCleanup?: boolean;
    /**
     * Whether to allow reading from the clipboard.
     * @default false
     */
    allowRead?: AllowRead;
    /**
     * How long before {@link GetClipboardReturn.isCopied | `GetClipboardReturn.isCopied`} is set to `false`.
     * @default 2000
     */
    copyDuration?: number;
    /**
     * Whether to fallback to the legacy `document.execCommand('copy')` for copying if the Clipboard API is not supported or not.
     * @default false
     */
    legacyCopy?: boolean;
};
type GetClipboardReturn = {
    readonly isSupported: boolean;
    readonly isCopied: boolean;
    /** The text currently in the clipboard. */
    readonly text: string;
    /** Copies text to the clipboard. */
    copyText: (value: string) => void;
    /** Cleans up the event listeners. */
    cleanup: CleanupFunction;
};
/**
 * Provides write (and optionally read) access to the text clipboard.
 * @param options Additional options to customize the behavior.
 * @see https://svelte-librarian.github.io/sv-use/docs/core/browser/get-clipboard-text
 */
export declare function getClipboardText<AllowRead extends boolean = false>(options?: GetClipboardOptions<AllowRead>): GetClipboardReturn;
export {};

Sources