PM> Install-Package Cloudcrate.AspNetCore.Blazor.Browser.Storage
Check out Steve Sanderson's demo at NDC Minnesota, at minute 48
Add Services to Dependency Injection
services.AddStorage();
Add Javascript file to your index.html
or _Host.cshtml
page in <body>
after either <script src="_framework/blazor.webassembly.js"></script>
or <script src="_framework/blazor.server.js"></script>
depending on what architecture you are using.
<script src="_content/Cloudcrate.AspNetCore.Blazor.Browser.Storage/Storage.js"></script>
Inject and use Storage
@using Cloudcrate.AspNetCore.Blazor.Browser.Storage;
@inject LocalStorage Storage
<input type="text" @bind="value" />
<button @onclick="SetValue">Set</button>
<button @onclick="GetValue">Get</button>
@code
{
string value;
void SetValue()
{
Storage.SetItem("storageKey", value);
}
void GetValue()
{
value = Storage.GetItem("storageKey");
}
}
Inject and use Storage
@using Cloudcrate.AspNetCore.Blazor.Browser.Storage;
@inject LocalStorage Storage
<input type="text" @bind="value" />
<button @onclick="SetValue">Set</button>
<button @onclick="GetValue">Get</button>
@code
{
string value;
async Task SetValue()
{
await Storage.SetItemAsync("storageKey", value);
}
async Task GetValue()
{
value = await Storage.GetItemAsync("storageKey");
}
}
Using storage
native event: StorageEvent
protected override void OnInit()
{
Storage.StorageChanged += HandleStorageChanged;
}
void HandleStorageChanged(object sender, StorageEventArgs e)
{
Console.WriteLine($"Value for key {e.Key} changed from {e.OldValue} to {e.NewValue}");
}
public void Dispose()
{
Storage.StorageChanged -= HandleStorageChanged;
}
- StorageEvent implementation by @peterblazejewicz
- Server-side support by @konradbartecki