How do I read the clipboard with blazor?
Andrew Henderson
I am using a Blazor Server application that have a screencasting feature. My goal is to get the data from clipboard and I am talking about not only a text which is easy but overall some img, files, texts etc.
I have a service named ClipboardService and it using Microsoft.JSInterop, I know for a fact that you can do something like this to get a text
public ValueTask<string> ReadTextAsync() { return _jsRuntime.InvokeAsync<string>("navigator.clipboard.readText");
}and you can use something like navigator.clipboard.read but it returns I suppose an empty array for my case. Tried to copy an image and sent it to viewer from blazor app and it just doesn't work how I expect it to work.
Clipboard service:
using Microsoft.JSInterop;
public sealed class ClipboardService
{ private readonly IJSRuntime _jsRuntime; public ClipboardService(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; } public ValueTask<string> ReadTextAsync() { return _jsRuntime.InvokeAsync<string>("navigator.clipboard.readText"); } public ValueTask WriteTextAsync(string text) { return _jsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", text); }
}Does anyone faced something familiar?
1 Answer
For managing textual content via Clipboard API you should use readText / writeText, but for images it should be read / write.
For for textual content you can use the service like in Gérald Barré example:
@page "/"
@inject ClipboardService ClipboardService
<h1>Demo Clipboard!</h1>
<button @onclick="ReadFromClipboard">Read from clipboard</button>
<button @onclick="CopyToClipboard">Copy to clipboard</button>
@text
@code { string text; async Task ReadFromClipboard() { // Reading from the clipboard may be denied, so you must handle the exception try { text = await ClipboardService.ReadTextAsync(); } catch { Console.WriteLine("Cannot read from clipboard"); } } async Task CopyToClipboard() { // Writing to the clipboard may be denied, so you must handle the exception try { await ClipboardService.WriteTextAsync(""); } catch { Console.WriteLine("Cannot write text to clipboard"); } }
}You can handle read/write operations for images similar way - e.g. via DOM canvas.toBlob. As a starting point, see post by Christian Liebel how to interact with Clipboard API to copy and paste images to/from clipboard.
Additional Links:
For mixed content I would recommend to have a closer look at how to handle
ClipboardItemin this post: Unblocking clipboard access by Jason Miller and Thomas SteinerRead nice overview of APIs - Clipboard API and deprecated Document.execCommand - for interacting with the clipboard in Copy to Clipboard in Blazor post by Chris Sainty.