ClipboardService Class

Provides access to the browser's clipboard API for reading and writing text.

public sealed class ClipboardService

Remarks

This service provides a convenient way to interact with the browser's clipboard in Blazor applications. To use this service, register it in your dependency injection container using ClipboardServiceExtensions.AddClipboard.

Example

Register the service in Program.cs: builder.Services.AddClipboard(); Use it in a component:

@inject ClipboardService ClipboardService

<button @onclick="CopyToClipboard">Copy</button>

@code {
    private async Task CopyToClipboard()
    {
        await ClipboardService.WriteTextAsync("Hello, World!");
    }
}

See also

Constructors

NameDescription
ClipboardService(IJSRuntime)Initializes a new instance of the ClipboardService class.

ClipboardService(IJSRuntime)

ClipboardService.cs

Initializes a new instance of the ClipboardService class.

public ClipboardService(IJSRuntime jsRuntime)

Parameters

jsRuntime IJSRuntime
The JavaScript runtime to use for interoperability.

Methods

NameDescription
ReadTextAsync(CancellationToken)Reads text from the clipboard.
WriteTextAsync(string, CancellationToken)Writes text to the clipboard.

ReadTextAsync(CancellationToken)

ClipboardService.cs

Reads text from the clipboard.

public ValueTask<string> ReadTextAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken
A cancellation token to cancel the operation.

Returns

ValueTask<string> A task that represents the asynchronous operation. The task result contains the text from the clipboard.

WriteTextAsync(string, CancellationToken)

ClipboardService.cs

Writes text to the clipboard.

public ValueTask WriteTextAsync(string text, CancellationToken cancellationToken = default)

Parameters

text string
The text to write to the clipboard.
cancellationToken CancellationToken
A cancellation token to cancel the operation.

Returns

ValueTask A task that represents the asynchronous operation.

Exceptions

JSException
The browser refused the write. This happens in a non-secure (non-HTTPS) context, when the clipboard permission is denied, or when the call does not originate from a user gesture. The failure is reported rather than swallowed so the caller does not report success for a copy that never happened.