How can I access the browsers localStorage in Blaz

2019-06-21 11:38发布

问题:

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)

回答1:

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



回答2:

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



回答3:

In case someone else is struggeling with this (as of juni-july 2018): Steve Sanderson addresses this very issue (localstorage) in his NDC conference video here: https://www.youtube.com/watch?v=JU-6pAxqAa4 from around minute 45 or so.

He uses a a nuget package for this: https://github.com/cloudcrate/BlazorStorage Usage examples on the page, so no need to repat here.