Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

supportsClipboard

Checks if the Clipboard API is supported in the current environment.

TypeScript
Copied!
1/**
2 * Checks if the Clipboard API is supported in the current environment.
3 *
4 * @returns True if clipboard access is supported, false otherwise.
5 */
6export function supportsClipboard(): boolean {
7  return typeof navigator !== 'undefined' &&
8         typeof navigator.clipboard !== 'undefined';
9}
  • Environment-Safe Check

    Guards against ReferenceError in non-browser or server environments by validating the presence of navigator.

  • Minimal Overhead

    Performs a direct, fast property check with no side effects or dependencies.

  • Prevents Runtime Failures

    Helps avoid calling unsupported clipboard methods, which could otherwise result in unhandled exceptions or user-facing errors.

  • Useful for Conditional Feature Logic

    Enables clean branching for fallback mechanisms or alternative UIs based on clipboard availability.

Tests | Examples

TypeScript
Copied!
1test('supportsClipboard - should return true if navigator.clipboard exists', () => {
2  const originalNavigator = global.navigator;
3  global.navigator = { clipboard: {} } as Navigator;
4  expect(supportsClipboard()).toBe(true);
5  global.navigator = originalNavigator;
6});
7
8test('supportsClipboard - should return false if navigator is undefined', () => {
9  const originalNavigator = global.navigator;
10  // @ts-expect-error
11  delete global.navigator;
12  expect(supportsClipboard()).toBe(false);
13  global.navigator = originalNavigator;
14});
15
16test('supportsClipboard - should return false if navigator.clipboard is undefined', () => {
17  const originalNavigator = global.navigator;
18  global.navigator = {} as Navigator;
19  expect(supportsClipboard()).toBe(false);
20  global.navigator = originalNavigator;
21});

Common Use Cases

  • Feature Detection for Copy Buttons

    Check support before rendering or enabling "Copy to Clipboard" UI elements.

  • Progressive Enhancement

    Add clipboard functionality only when supported, falling back to input selection or other strategies.

  • Clipboard-Based Sharing or Exporting

    Validate clipboard access before triggering actions like copying URLs, text snippets, or code blocks.

  • Testing Clipboard Integration

    Used in automated test suites or dev tools to conditionally run clipboard-related logic.

Codebase: Utilities -> Platforms -> supportsClipboard | Yevhen Klymentiev