Update the HTML head from your Blazor components

Published on

When you spin up a Blazor app and start navigating between pages you immediately run into an interesting problem.

Although it seems to your users like they’re switching between different pages on a web site, in reality they’re always hitting the same page (index.html for WASM or _Host.cshtml for Server) and Blazor is switching different content ‘on’ and ‘off’ (showing/hiding).

In fact this is how all SPA (single page applications) work.

But what if you want to update the page title from your code?

One of the examples in Blazor by Example has you create a little timer (Pomodoro timer) which counts down from 25 minutes and then uses a little javascript to dynamically show the current value of the timer in the browser’s title…

So how is this achieved?

.NET 3.1

The only way to pull this trick off pre .NET 5 is to use a little javascript.

You can declare the javascript (in index.html if you’re using Blazor WASM or _Host.cshtml if Server):

<script>
window.setTitle = (title) => document.title = title;
</script>

Then in your Blazor components, inject the IJSRuntime

@inject IJSRuntime JSRuntime

Before finally invoking the setTitle javascript method from your component…

JSRuntime.InvokeVoidAsync("setTitle", remaining);

.NET 5

Happily this problem is solved with .NET 5 where you can now use dedicated components to achieve the same result.

First you’ll need to add a package reference:

Terminal window
dotnet add package Microsoft.AspNetCore.Components.Web.Extensions

Then include a script reference (in index.html or _Host.cshtml):

<script src="_content/Microsoft.AspNetCore.Components.Web.Extensions/headManager.js"></script>

From here you’re free to use Title, Link and Meta components to set the page’s title, or dynamically add link and meta tags to the HTML head.

@using Microsoft.AspNetCore.Components.Web.Extensions.Head
<Title Value="@remaining"></Title>
@code {
private string remaining { get;set; }
}

Pretty handy huh?

Oh, and remember you can move that @using statement to _Imports.razor (to save declaring it in every component).

All posts in To .NET 5 and beyond
  1. Does .NET 6 fix Blazor Prerendering?
  2. Update the HTML head from your Blazor components
  3. From site.css to component styles
  4. Render Blazor WASM components in your existing MVC/Razor Pages applications
  5. Prerendering your Blazor WASM application with .NET 5 (part 1)
  6. Prerendering your Blazor WASM application with .NET 5 (part 2 - solving the missing HttpClient problem)

I know you don't have endless hours to learn ASP.NET

Cut through the noise, simplify your web apps, ship your features. One high value email every week.

I respect your email privacy. Unsubscribe with one click.

    Next Up
    1. When does Blazor decide to render your UI?
    2. Render diagrams on the fly in your Blazor apps
    3. Making Scott Hanselman's Powerpoint Greenscreen trick work with RevealJS via Blazor Server