How can I access the browsers localStorage in Blazor?

asp.net-core blazor c#

Question

I want to support JWTs, so I need to keep the token around; is there some facility to access this? Or should we just be registering our own javascript function to access this functionality for now?

Edit: per advice, I attempted to use JS interop as :

<script>
    localStorage.setItem("key1", "key1data");
    Blazor.registerFunction("readStorage", (key) => {
        return localStorage.getItem(key);
    });
</script>
@if (jwtKey == null)
{
<div class="login-panel">
    <p>JWT not loaded</p>
</div>
}
else
{
<div class="login-panel">
    <p>@jwtKey</p>
</div>
}

@functions {
    public RenderFragment Body { get; set; }
    string jwtKey;

    protected override async Task OnInitAsync()
    {
        jwtKey = RegisteredFunction.Invoke<string>("readStorage", "key1");
        if (jwtKey == null)
        {
            jwtKey = "Unknown";
        }
    }
}

But this results in a WASM error in diag:

WASM: [Microsoft.AspNetCore.Blazor.Browser.Interop.JavaScriptException] Could not find registered function with name 'readStorage'. WASM: Error: Could not find registered function with name 'readStorage'.

FYI, this is in the MainLayout.cshtml of the Blazor VS boilerplate project.

(can make a new Question if appropriate; somewhat related to this one though)

Accepted Answer

For 0.1 you need to write your own javascript interop. But I believe this is something worked on, and maybe in the 0.2 release.

Alternatively (if you don't need storage between sessions) you can write your own DI singleton, like done here: https://github.com/aspnet/samples/blob/master/samples/aspnetcore/blazor/FlightFinder/FlightFinder.Client/Services/AppState.cs

Edit
There is an open PR for this, so indeed should be there soon: https://github.com/aspnet/Blazor/pull/205

Edit2 0.2 is done, but no localstorage yet. In the meantime i've developed a package for this: BlazorExtensions also on nuget


Popular Answer

It might be implemented by default into Blazor but for now I'm using: Nuget - BlazorStorage




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why