ClipboardService Class
Provides access to the browser's clipboard API for reading and writing text.
public sealed class ClipboardServiceRemarks
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
| Name | Description |
|---|---|
| ClipboardService(IJSRuntime) | Initializes a new instance of the ClipboardService class. |
ClipboardService(IJSRuntime)
ClipboardService.csInitializes a new instance of the ClipboardService class.
public ClipboardService(IJSRuntime jsRuntime)Parameters
jsRuntimeIJSRuntime- The JavaScript runtime to use for interoperability.
Methods
| Name | Description |
|---|---|
| ReadTextAsync(CancellationToken) | Reads text from the clipboard. |
| WriteTextAsync(string, CancellationToken) | Writes text to the clipboard. |
ReadTextAsync(CancellationToken)
ClipboardService.csReads text from the clipboard.
public ValueTask<string> ReadTextAsync(CancellationToken cancellationToken = default)Parameters
cancellationTokenCancellationToken- 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.csWrites text to the clipboard.
public ValueTask WriteTextAsync(string text, CancellationToken cancellationToken = default)Parameters
textstring- The text to write to the clipboard.
cancellationTokenCancellationToken- 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.