.netmaui-blazor

.NET MAUI Hybrid Blazor Copy to Clipboard


I've found a few resources on how to copy to clipboard within MAUI Native, plus within Blazor Server, but I'm wondering how can you get copy to clipboard working on a Blazor page within a .NET MAUI Hybrid app?

Here's a resource from MS on native: https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/data/clipboard?view=net-maui-8.0


Solution

  • You can jsut use the Maui ClipBoard api to do that:

    <button class="btn btn-primary" @onclick="Copy">Copy</button>
    <button class="btn btn-primary" @onclick="Paste">Paste</button>
    <InputText @bind-Value="@value"/>
    @code{
        public string value;
        public async void Copy()
        {
            await Clipboard.Default.SetTextAsync("Copy to Click");
        }
        public async void Paste()
        {
            value = await Clipboard.Default.GetTextAsync();
        }
    }
    

    Or you can call the javascript to do that:

    @inject IJSRuntime js;
    <button class="btn btn-primary" @onclick="Copy">Copy</button>
    <button class="btn btn-primary" @onclick="Paste">Paste</button>
    <InputText @bind-Value="@value" />
    
    @code {
        public string value;
        public async void Copy()
        {
            js.InvokeVoidAsync("navigator.clipboard.writeText", "Copy to clipboard");
        }
        public async void Paste()
        {
            //value = await js.InvokeAsync<string>("navigator.clipboard.readText");
            // this can't work for android because the navigator.clipboard.readText is not compatible with the Android WebView
        }
    }
    

    Note: The javascript paste will crash on the Android, so using the .net maui clipboard api is better.