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)
Just go to the developer tools by pressing F12 , then go to the Application tab. In the Storage section expand Local Storage. After that, you'll see all your browser's local storage there. In Chrome version 65, you can manually modify and add new items.
The localStorage read-only property of the window interface allows you to access a Storage object for the Document 's origin; the stored data is saved across browser sessions.
JavaScript localStorage methods There are four basic JavaScript methods you can use to access and work with localStorage: setItem() - takes a key-value pair and adds it to localStorage. getItem() - takes a key and returns the corresponding value. removeItem() - takes a key and removes the corresponding key-value pair.
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
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