How to copy to clipboard using Blazor's JsRuntime

How to copy to clipboard using Blazor's JsRuntime

28 Oct 2025

Here's the full explanation for copying text to the clipboard using Blazor's JsRuntime:

Step 1: Injecting IJSRuntime

In your Razor component, you need to inject an instance of IJSRuntime. This is done by adding a line at the top of your component:

@inject IJSRuntime JSRuntime

This injects an instance of IJSRuntime, which provides a way to interact with JavaScript and access browser APIs.

Step 2: Defining the copy function

In your codebehind, you need to define a method that will copy text to the clipboard. Let's call this method CopyToClipboard. This method takes a string argument (the text to copy):

protected async Task CopyToClipboardAsync(string text)
{
    // Implement copying logic here
}

Step 3: Calling the browser API

In your CopyToClipboardAsync method, you use the InvokeVoidAsync method of IJSRuntime to call the browser's navigator.clipboard.writeText() API directly. This function takes a string argument (the text to copy) and sets it to the clipboard:

protected async Task CopyToClipboardAsync(string text)
{
    await JSRuntime.InvokeVoidAsync("navigator.clipboard.writeText", text);
}

Note that we're passing text as an argument to the InvokeVoidAsync method, which is then passed on to the browser's API.

What happens behind the scenes

When you call InvokeVoidAsync, Blazor uses a technique called "interoperability" to communicate with JavaScript. This involves:

  1. Compiling your C# code into JavaScript
  2. Creating a bridge between the two using WebAssembly (WASM)
  3. Executing the resulting JavaScript code in the browser

In this case, the compiled JavaScript code calls navigator.clipboard.writeText() and passes in the text to copy.

Using the method

You can now call the CopyToClipboard method from your Razor component:

<button @onclick="() => CopyToClipboardAsync("Hello World!")">Copy</button>

This will copy the text "Hello World!" to the clipboard when the button is clicked.

That's it! This approach allows you to copy text to the clipboard using Blazor's JsRuntime without needing any custom JavaScript code.


Every now and then I have to prioritize work, life or other matters but we'll soon continue with the ML Basics on YouTube

Kind regards, Auguste @ kiss-code


Join the community

I continuously build, learn and experiment with innovative technology. Allow me to share what I learn, with you.

Newsletter

Allow me to share what I learn, with you.

Share

Support

An error has occurred. 🗙