Logo

Want to display the current connection status in your Blazor Webassembly project but aren't sure how? Neither was I, so I set about finding out how. Read on to find out how you can too.

Showing Connection Status in Blazor Webassembly

Whilst experimenting with the new Blazor WebAssembly framework I wanted to display a notification to the end user when they were working offline and no longer connected to the internet. I was hoping that there was a built in control that would provide this functionality but unfortunately at the time of writing there isn't. However, it does come with the tools for you to build it yourself in the form of the JavaScript Interop, this feature provides you with the ability to invoke JavaScript functions from .NET methods and .NET methods from JavaScript functions.

This article will show you how you can use the JavaScript Interop to hook in to the JavaScript Navigator API to update a Blazor component with the current connection status. All code in the article can be found in my GitLab repository, direct link at the foot of the article.

The Idea

The JavaScript Navigator API exposes the function onLine which returns the online state of the browser, it has broad browser support and by hooking up an event listener through the JavaScript interop we can then display the user their current connection status.

    
var online = window.navigator.onLine;
    

The Razor Component

First we'll create a simple razor component that will display one of two content fragments depending on the current connection status. The component exposes a function OnConnectionStatusChanged which is decorated with the attribute [JSInvokable("Connection.StatusChanged")], this indicates that the function can be invoked from JavaScript with the function name Connection.StatusChanged.

    
@inject IJSRuntime JsRuntime;

@if (IsOnline)
{
    @Online
}
else
{
    @Offline
}

@code {

    [Parameter]
    public RenderFragment Online { get; set; }

    [Parameter]
    public RenderFragment Offline { get; set; }

    public bool IsOnline { get; set; }

    [JSInvokable("Connection.StatusChanged")]
    public void OnConnectionStatusChanged(bool isOnline)
    {
        if (IsOnline != isOnline)
        {
            IsOnline = isOnline;
        }

        StateHasChanged();
    }
}
    

As it is, our component doesn't do very much, the property IsOnline is always false, to rectify this we need some JavaScript to hook it up to.

The JavaScript

Our JavaScript needs adds an event listener to the online and offline events so that we can display the connection status to the user. To do this the Initialize function creates a new event handler function that calls the OnStatusChanged event in our Razor component. We also create a Dispose function to remove the handler so that we can tidy up after ourselves.

    
let handler;

window.Connection = {
    Initialize: function (interop) {

        handler = function () {
            interop.invokeMethodAsync("Connection.StatusChanged", navigator.onLine);
        }

        window.addEventListener("online", handler);
        window.addEventListener("offline", handler);

        handler(navigator.onLine);
    },
    Dispose: function () {

        if (handler != null) {

            window.removeEventListener("online", handler);
            window.removeEventListener("offline", handler);
        }
    }
};
    

Tying It All Together

So with our JavaScript written we need to tie it back in to our Razor component so that it actually does something, so here's our updated Razor component code. The two main things to note are where we have overridden the OnInitialized component event and implemented the IDisposable interface. When the OnInitialized event fires it calls the Connection.Initialize JavaScript function and registers itself as the handler so that it can respond to changes in the users connection state. When the Dispose event fires it calls the Connection.Dispose JavaScript function to remove the handler.

    
@implements IDisposable
@inject IJSRuntime JsRuntime;

@if (IsOnline)
{
    @Online
}
else
{
    @Offline
}

@code {

    [Parameter]
    public RenderFragment Online { get; set; }

    [Parameter]
    public RenderFragment Offline { get; set; }

    public bool IsOnline { get; set; }

    [JSInvokable("Connection.StatusChanged")]
    public void OnConnectionStatusChanged(bool isOnline)
    {
        if (IsOnline != isOnline)
        {
            IsOnline = isOnline;
        }

        StateHasChanged();
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        JsRuntime.InvokeVoidAsync("Connection.Initialize", DotNetObjectReference.Create(this));
    }

    public void Dispose()
    {
        JsRuntime.InvokeVoidAsync("Connection.Dispose");
    }
}
    

Now all that's left to do is to update your index.html file to inlucde a reference to the JavaScript file and embed the Connection component on a page. You can pass in any code fragment to to the component as the Online or Offline parameters, or just populate the Offline parameter if you only want to show a notice when the user is working offline. The choice, as they say, is yours!

    
<Connection>
    <Online>
        <h1 style="color: green">Online</h1>
    </Online>
    <Offline>
        <h1 style="color: red">Offline</h1>
    </Offline>
</Connection>
    

Get in touch

If you have got a project that you'd like my help with or a question about any of the articles I've posted on the site then fill in the contact form and send me an email and I will endeavor to get back to you as soon as possible.