As Blazor being a SPA framework, I would like to know is it possible to set a page title for each individual page in Blazor?
I am currently working on Blazor webassembly project and cannot figure out a way how to add a page title since there is only one index.html as it should be in SPA, but would be really useful if it can be achieved to set title for each "page".
Blazor doesn't provide any built-in method to change the page title. This means you need to call a JS function to update the document title. The page title is updated when you set the Title parameter.
You can get the current page title in Blazor by using the “title” property of the document object in JavaScript and by using a . JavaScript interop since there is no DOM accessibility in Blazor.
Note: starting with .Net 6.0 there is official support for changing the title, so the solution below is no longer needed.
Provide following script in your index.html (or in an included .js file):
<script>
setTitle = (title) => { document.title = title; };
</script>
In each page inject the jsinterop:
@inject IJSRuntime JSRuntime;
After each render, set the document title to the value of your choice:
@code
{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeVoidAsync("setTitle", "this is the new title"); ;
}
}
In ASP.NET CORE 5.0, a new component for Title is added
<Title value="Page title" />
Msdn Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/additional-scenarios?view=aspnetcore-5.0#influence-html-head-tag-elements
First add the using statement in the component
@using Microsoft.AspNetCore.Components.Web.Extensions.Head
You can install (if not installed) using the command.
dotnet add package Microsoft.AspNetCore.Components.Web.Extensions --version 5.0.0-preview9.20467.1
5.0.0-preview9.20467.1 is the version when I am writing this. Please check the nuget url for the latest version
Nuget url: https://www.nuget.org/packages/Microsoft.AspNetCore.Components.Web.Extensions/
Then add the Title tag.
<Title Value="My page title" />
See the sample output image below
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With