如何访问Blazor中的浏览器localStorage? [英] How can I access the browsers localStorage in Blazor?

查看:1041
本文介绍了如何访问Blazor中的浏览器localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想支持JWT,所以我需要保留令牌.有一些设施可以访问吗?还是我们现在应该注册自己的javascript函数以访问此功能?

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?

根据建议,我尝试将JS互操作用作:

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";
        }
    }
}

但这会导致诊断中出现WASM错误:

But this results in a WASM error in diag:

WASM: [Microsoft.AspNetCore.Blazor.Browser.Interop.JavaScriptException] 找不到名称为"readStorage"的注册功能. WASM: 错误:找不到名称为"readStorage"的注册功能.

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

仅供参考,这位于Blazor VS样板项目的MainLayout.cshtml中.

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)

推荐答案

对于0.1,您需要编写自己的javascript互操作.但是我相信这是可行的,也许是在0.2版本中.

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.

或者(如果您不需要在会话之间存储),您可以编写自己的DI单例,如此处所示:

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

修改
有一个开放的PR,所以确实应该很快出现:
https://github.com/aspnet/Blazor/pull/205

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

Edit2 0.2已经完成,但是还没有本地存储.同时,我为此开发了一个软件包: BlazorExtensions 也在nuget上

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

这篇关于如何访问Blazor中的浏览器localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆