Search code examples
blazor

How to set page title in blazor?


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".


Solution

  • Note: starting with .Net 6.0 there is official support for changing the title, so the solution below is no longer needed.

    1. Provide following script in your index.html (or in an included .js file):

      <script>
           setTitle = (title) => { document.title = title; };
      </script>
      
    1. In each page inject the jsinterop:

      @inject IJSRuntime JSRuntime;
      
    2. 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"); ;        
         }    
      }