Skip to content
GitHub11 stars

Copies text to the clipboard and writes cookies from the browser.

Two small helpers the styled components need: BrowserClipboard copies text, for a code block's copy button, and BrowserCookies writes a cookie, for a sidebar that remembers whether it was open. Both run in the browser, through the JavaScript runtime you pass them.

Clipboard

CopyAsync returns false when the browser refuses, such as without permission or outside a secure context:

CopyButton.razor
@inject IJSRuntime JS

<button type="button" @onclick="CopyAsync">@(_copied ? "Copied" : "Copy")</button>

@code {
    [Parameter] public string Text { get; set; } = "";

    private bool _copied;

    private async Task CopyAsync() => _copied = await BrowserClipboard.CopyAsync(JS, Text);
}

Cookies

SetAsync sets a cookie for the whole site, kept for the time you give it:

Sidebar.razor
@inject IJSRuntime JS

@code {
    private async Task RememberAsync(bool open) =>
        await BrowserCookies.SetAsync(JS, "sidebar_state", open ? "true" : "false", TimeSpan.FromDays(7));
}

API Reference

BrowserClipboard

BrowserCookies