DEV Community

Cover image for Call browser APIs from Blazor without writing JavaScript
Todd Tanner
Todd Tanner

Posted on Originally published at spawndev.com

Call browser APIs from Blazor without writing JavaScript

Live demo | Full example on GitHub

You are following a recipe on your phone. Your hands are covered in flour, and the screen goes dark.

Browsers have a fix for this, the Screen Wake Lock API. Blazor has no built-in wrapper for it, so the usual route is a JavaScript module, an IJSRuntime import, and a string name for every function you call. A typo in one of those strings shows up at run time.

This article does it in C# instead. We will build a small recipe page that keeps the screen on, takes the lock back when you return to the tab, and copies the ingredients to the clipboard. You need the .NET 10 SDK and a browser.

The usual way

With plain Blazor interop you write a JavaScript file first:

let sentinel;
export async function lock() {
    sentinel = await navigator.wakeLock.request("screen");
}
export async function unlock() {
    await sentinel?.release();
}
Enter fullscreen mode Exit fullscreen mode

Then you import it and call it by name. That is fine for one function. It gets harder when JavaScript needs to call you back, because you then also manage a DotNetObjectReference and its lifetime.

Set up SpawnJS

SpawnDev.SpawnJS wraps browser APIs as C# classes. Create a Blazor WebAssembly app and add two packages:

dotnet new blazorwasm -o BrowserApis --empty
cd BrowserApis
dotnet add package SpawnDev.SpawnJS
dotnet add package SpawnDev.SpawnJS.Blazor
Enter fullscreen mode Exit fullscreen mode

In Program.cs, add AddSpawnJSRuntime() and start the app with SpawnJSRunAsync():

using BrowserApis;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SpawnDev.SpawnJS;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

builder.Services.AddSpawnJSRuntime();

await builder.Build().SpawnJSRunAsync();
Enter fullscreen mode Exit fullscreen mode

The build may show warning CA1416 on AddSpawnJSRuntime(). It says the call needs a browser, which a Blazor WebAssembly app is, so you can ignore it.

Add these lines to _Imports.razor:

@using SpawnDev.SpawnJS
@using SpawnDev.SpawnJS.JSObjects
Enter fullscreen mode Exit fullscreen mode

The template comes with a page at /, Pages/Home.razor. Delete it and add your own, Pages/CookMode.razor. The next sections explain its main parts, and the whole file is at the end.

Keep the screen on

In JavaScript the call is navigator.wakeLock.request(). In C# it has the same shape:

async Task KeepScreenOn()
{
    if (screenLock is not null) return;
    using var navigator = new Navigator();
    using var wakeLock = navigator.WakeLock;
    if (wakeLock is null)
    {
        cookMode = false;
        status = "This browser cannot keep the screen on.";
        return;
    }
    try
    {
        var granted = await wakeLock.Request();
        if (!cookMode || screenLock is not null)
        {
            // Stopped, or already locked, while the request was in flight.
            await granted.Release();
            granted.Dispose();
            return;
        }
        screenLock = granted;
        screenLock.OnRelease += ScreenLock_OnRelease;
        status = "";
    }
    catch (Exception ex)
    {
        // The browser can refuse, for example on low battery.
        cookMode = false;
        status = $"The browser refused: {ex.Message}";
    }
}
Enter fullscreen mode Exit fullscreen mode

Three things to notice:

  • Feature detection is a null check. navigator.WakeLock is null when the browser does not have the API.
  • Promises are Tasks. You await them, and a rejected promise is an exception you can catch.
  • using matters. Each wrapper holds a reference to a live JavaScript object. Disposing the wrapper lets go of it.

Listen to browser events

Browsers release the lock when the tab is hidden, so switching apps to answer a message turns the feature off. To take it back, listen for the page becoming visible again:

protected override void OnInitialized()
{
    document = JS.GetDocument();
    document!.OnVisibilityChange += Document_OnVisibilityChange;
}
Enter fullscreen mode Exit fullscreen mode
// Take the lock back when the visitor returns to the tab.
async void Document_OnVisibilityChange()
{
    if (document is null || document.Hidden || !cookMode) return;
    await KeepScreenOn();
    StateHasChanged();
}
Enter fullscreen mode Exit fullscreen mode

Subscribing is += and unsubscribing is -=, like any C# event. Match every += with a -= before you dispose the object. Otherwise the browser can call into a component that no longer exists.

Copy to the clipboard

The same pattern works for other APIs:

async Task CopyIngredients()
{
    using var navigator = new Navigator();
    using var clipboard = navigator.Clipboard;
    try
    {
        await clipboard.WriteText(string.Join("\n", ingredients));
        status = "Copied.";
    }
    catch (Exception ex)
    {
        status = $"Could not copy: {ex.Message}";
    }
}
Enter fullscreen mode Exit fullscreen mode

Clipboard access needs a secure context, so it works on https:// and localhost, and browsers may require that the call comes from a click.

Clean up

public async ValueTask DisposeAsync()
{
    cookMode = false;
    if (document is not null)
    {
        document.OnVisibilityChange -= Document_OnVisibilityChange;
        document.Dispose();
        document = null;
    }
    await LetScreenSleep();
}
Enter fullscreen mode Exit fullscreen mode

When there is no wrapper

You can call anything by name, including a function from a third-party script:

// JavaScript: btoa("Hello")
var encoded = JS.Call<string, string>("btoa", "Hello");
Enter fullscreen mode Exit fullscreen mode

Argument types come first and the return type comes last. Get reads a property, and Call runs a method.

The whole page

@page "/"
@inject SpawnJSRuntime JS
@implements IAsyncDisposable

<main>
    <h1>Pancakes</h1>
    <ul>
        @foreach (var item in ingredients)
        {
            <li>@item</li>
        }
    </ul>
    <button id="cook" @onclick="ToggleCookMode">@(cookMode ? "Stop cook mode" : "Start cook mode")</button>
    <button id="copy" @onclick="CopyIngredients">Copy ingredients</button>
    <p id="screen">Screen: @(screenLock is null ? "may sleep" : "staying on")</p>
    <p id="status" role="status">@status</p>
</main>

@code {
    readonly string[] ingredients = ["2 cups flour", "2 eggs", "1 1/2 cups milk", "1 tbsp sugar"];
    Document? document;
    WakeLockSentinel? screenLock;
    bool cookMode;
    string status = "";

    protected override void OnInitialized()
    {
        document = JS.GetDocument();
        document!.OnVisibilityChange += Document_OnVisibilityChange;
    }

    async Task ToggleCookMode()
    {
        cookMode = !cookMode;
        if (cookMode) await KeepScreenOn();
        else await LetScreenSleep();
    }

    async Task KeepScreenOn()
    {
        if (screenLock is not null) return;
        using var navigator = new Navigator();
        using var wakeLock = navigator.WakeLock;
        if (wakeLock is null)
        {
            cookMode = false;
            status = "This browser cannot keep the screen on.";
            return;
        }
        try
        {
            var granted = await wakeLock.Request();
            if (!cookMode || screenLock is not null)
            {
                // Stopped, or already locked, while the request was in flight.
                await granted.Release();
                granted.Dispose();
                return;
            }
            screenLock = granted;
            screenLock.OnRelease += ScreenLock_OnRelease;
            status = "";
        }
        catch (Exception ex)
        {
            // The browser can refuse, for example on low battery.
            cookMode = false;
            status = $"The browser refused: {ex.Message}";
        }
    }

    async Task LetScreenSleep()
    {
        var released = DetachLock();
        if (released is null) return;
        await released.Release();
        released.Dispose();
    }

    // The browser releases the lock itself when the tab is hidden.
    void ScreenLock_OnRelease()
    {
        DetachLock()?.Dispose();
        StateHasChanged();
    }

    // Take the lock back when the visitor returns to the tab.
    async void Document_OnVisibilityChange()
    {
        if (document is null || document.Hidden || !cookMode) return;
        await KeepScreenOn();
        StateHasChanged();
    }

    async Task CopyIngredients()
    {
        using var navigator = new Navigator();
        using var clipboard = navigator.Clipboard;
        try
        {
            await clipboard.WriteText(string.Join("\n", ingredients));
            status = "Copied.";
        }
        catch (Exception ex)
        {
            status = $"Could not copy: {ex.Message}";
        }
    }

    WakeLockSentinel? DetachLock()
    {
        var current = screenLock;
        screenLock = null;
        if (current is not null) current.OnRelease -= ScreenLock_OnRelease;
        return current;
    }

    public async ValueTask DisposeAsync()
    {
        cookMode = false;
        if (document is not null)
        {
            document.OnVisibilityChange -= Document_OnVisibilityChange;
            document.Dispose();
            document = null;
        }
        await LetScreenSleep();
    }
}
Enter fullscreen mode Exit fullscreen mode

Run it

Run dotnet run in your project, or clone the finished one:

git clone https://github.com/LostBeard/SpawnDev.Examples
cd SpawnDev.Examples/BrowserApis
dotnet run
Enter fullscreen mode Exit fullscreen mode

Already using SpawnDev.BlazorJS? It offers the same style of typed wrappers and stays supported. SpawnJS is the newer library, and it also runs outside Blazor. Both are MIT licensed, with all work done in public, so you can use them and fork them.

Top comments (0)