Blazor Interop LocalStorage 0.4.0 change to 0.5.1

blazor c# javascript

Question

I am learning how to use Blazor Interop, but it has changed recently, so I don't have any easy example to learn from I copied a code from a working example and would like to change it to the new interop here is the code from Blazor 0.4.0 from .js file

Blazor.registerFunction('saveToken', token => {
window.localStorage.setItem('jwt', token);
console.log("Authentication token has been stored.");
return true;

});

And this from the Blazor page .csthml functions

            RegisteredFunction.Invoke<bool>("saveToken", token);

I have already read the Blazor Doc Interop https://blazor.net/docs/javascript-interop.html and the example was very easy to follow, but with localstorage I don't know how

Accepted Answer

In 0.5+, you just make the function visible through window.

window.saveToken = token => {
    window.localStorage.setItem('jwt', token);
    console.log("Authentication token has been stored.");
    return true;
};

JsRuntime.Current.InvokeAsync<bool>("saveToken", token);

Popular Answer

Or, you can just use a Nuget package that already does the interop for you like this one: https://github.com/BlazorExtensions/Storage




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