Repository navigation
Description
Background and Motivation
Blazor applications use string-based IJSRuntime calls to access standard browser APIs. This proposal adds typed access through a new Microsoft.AspNetCore.Components.Platform package. The first supported API is Web Storage.
The scope excludes DOM APIs and application-specific JavaScript.
The prototype is available in kotlarmilos#1. The trimming update is available in kotlarmilos#2.
The implementation is in #69305.
Proposed API
+namespace Microsoft.AspNetCore.Components.Platform;
+
+public interface IBrowserPlatform
+{
+ Window Window { get; }
+}
+
+public sealed class Window
+{
+}
+
+public sealed class Storage
+{
+ public ValueTask<uint> GetLengthAsync();
+ public ValueTask<string?> KeyAsync(uint index);
+ public ValueTask<string?> GetItemAsync(string key);
+ public ValueTask SetItemAsync(string key, string value);
+ public ValueTask RemoveItemAsync(string key);
+ public ValueTask ClearAsync();
+}
+
+public static class WindowWebStorageExtensions
+{
+ extension(Window window)
+ {
+ public Storage LocalStorage { get; }
+ public Storage SessionStorage { get; }
+ }
+}
+
+namespace Microsoft.Extensions.DependencyInjection;
+
+public static class BrowserPlatformServiceCollectionExtensions
+{
+ public static IServiceCollection AddBrowserPlatform(
+ this IServiceCollection services);
+}Comparison with Web API
| Web API (Web IDL) | C# public API |
|---|---|
|
|
Window has no public members or constructors. It is the entry point for extension properties such as LocalStorage, and applications get it only from IBrowserPlatform.
Window and Storage do not implement IAsyncDisposable. Window hands the same instance to every caller, so application code must not dispose it. The DI scope disposes them through an internal interface.
The storage methods do not take a CancellationToken. Canceling a JS interop call does not stop the result from being sent to .NET, so it saves little. This also matches ProtectedBrowserStorage, and an overload can be added later if needed.
Usage Examples
builder.Services.AddBrowserPlatform();@using Microsoft.AspNetCore.Components.Platform
@inject IBrowserPlatform Browser
@code {
private async Task SaveAndLoadAsync()
{
await Browser.Window.LocalStorage.SetItemAsync("key", "value");
var value = await Browser.Window.LocalStorage.GetItemAsync("key");
}
}The API works in Interactive Server and WebAssembly.
Alternative Designs
Applications can continue to use IJSRuntime directly. Separate storage services would work for Web Storage but would not provide a common shape for other browser APIs.
Exposing the Web Storage API on the Window object as regular properties is easier to discover, but implementing it as extension properties lets you trim unused API.
We also considered a public feature map, but it remains internal at least in the first release of this proposal because public extensibility raises many considerations, such as rules for keys, type safety, and conflicts.
Risks
The package could grow too broadly. Each browser API family should therefore remain small and separately reviewable.
Extension properties require the correct namespace import and might be harder to discover. Their trimming behavior has been verified manually.
Web Storage is unavailable before interactivity and stores raw, unprotected strings.
Activity
github-actions commentedon Sep 15, 2026
Triage Summary
Area:
area-blazor(proposal adds a newMicrosoft.AspNetCore.Components.Platformpackage for typed browser API access in Blazor, starting with Web Storage)Type:
Feature(preserved)Potential Duplicates
jsakamotoIGJP commentedon Sep 15, 2026
Hi @kotlarmilos. I opened this proposal based on our prototype. Would you be willing to champion it for API review? I would also appreciate feedback from @maraf and @javiercn.
I am also preparing a draft PR against this repository and plan to open it today or tomorrow.
kotlarmilos commentedon Sep 16, 2026
Thanks, I will help with the API review.
jsakamotoIGJP commentedon Sep 17, 2026
@kotlarmilos One part of the proposed API above needs a change.
StorageandWindowshould not implementIAsyncDisposablepublicly.Windowcreates both objects and hands the same instance to every caller, so a dispose from application code leaves the rest of the scope unusable. In the prototype, they now implement the interface explicitly, the wayOwningComponentBasedoes, and the DI scope still disposes the whole graph through an internal type.Here is the change against the API above.
Windowhas no public members, which matches its role. The storage properties come from the extension, and the type itself is only a handle.This removes
DisposeAsyncfrom IntelliSense and the public API, preventing users from disposing of it in most cases. Butawait using var storage = browser.Window.LocalStorage;still works, so it's not "perfect."If we want a perfect solution in that case, splitting the surface into
IWindowandIStoragewould turn that into a compile error. Instead, the cost is that a public interface is harder to version than a sealed class, and this package is meant to grow one browser API family at a time. I would like the review to settle which side to take.The draft PR is #69305.
KristofferStrube commentedon Sep 23, 2026
Hey @jsakamotoIGJP hope you are good! 😁
I'm very interested in JSInterop and browser APIs as you know, so I wanted to chime in. I think it is really cool that we could potentially get more browser APIs exposed directly from Blazor and I can't wait to contribute if this gets through. 😊
If this is to be the start of a series of APIs that implement wrappers for browser APIs then I guess we are already making some decisions that will influence the patterns that we will follow for future APIs as we want to handle the same problems consistenly in all the APIs.
If we are to be inspired by what is already present in Blazor, then we could look at the
NavigationManager, which is a abstration over some of the members of theNavigatorWebIDL type. TheNavigationManageris not a 1-to-1 wrapper for theNavigator, and I guess there are multiple reasons for this. It is first of all a class that has evolved as Blazor has had more needs for the features the theNavigatorexposes, and secondly it has some parts that are built to be more ergonomic for .NET developers instead of supplying exactly the same surface as theNavigator(e.g.NavigatoTo). There are also features of theNavigatorthat are not exposed through theNavigationManagerat all, not because it would be difficult to expand, but because that would be an extra API surface that needs to be maintained, which very few might use (e.g.backandforward).Another option for the
NavigationManagercould have been that it should mimick the WebIDL specification forNavigator1-to-1. This would have been more feature complete (which would be a good thing), but instead it might not be as ergonomic.So when we want to expose the capabilities that are described in the Web storage section of the HTML WebIDL specification, then I think we can decide on one of two ways. We can expose the most useful parts in a .NET idiomatic way or we can expose some parts 1-to-1. Right now it seems like it is mostly a 1-to-1 solution that we are going for. If we were not limited by this, then we could create something that is simpler.
In the above, we have removed members that would probably not be used a lot like
length, andkey. And we have called the methods something simpler instead of leaning towards parity with the naming in the specification. These two types are also the ones that would be registered directly in the DI container just likeNavigationManager, so we could just inject them where we need them instead of accessing them through theIBrowserPlatform.Another thing I'm unsure about, is the use of
ValueTask. I know that JSInterop uses it for its API surface, but I don't know why that is either. As I remember, it is only more performant to useValueTaskif it is frequently going to be returned immediately, but I guess this is not the case as JSInteorop will create a task underneath that will be resolved once the underlying response is returned (I don't know if this has changed). @javiercn might be able to give some insight on this. Apart from thisValueTaskhas more restrictions about how it can be used.With small self-contained APIs like the ones above it will be easy to expand with others in the future. One of the drawbacks of this design is however discoverability as you will no longer have all APIs accessible through the
IBrowserPlatformtype.What do you think?
jsakamotoIGJP commentedon Sep 24, 2026
Hi @KristofferStrube, long time no see! 😀
Thanks for the feedback. I've used some of your browser API packages before, so I’m happy to hear your thoughts on this.
You are correct that this proposal intentionally follows the "1-to-1 mapping" direction.
I agree that a more .NET-style design, with separate injectable services such as LocalStorage and SessionStorage, is also a valid and attractive approach. In fact, many community libraries seem to go that way.
For this proposal, however, I wanted to prioritize a different developer experience. My goal is that if a developer already knows the Web Platform API, they can find the corresponding Blazor API without learning any additional Blazor-specific concepts. The idea is to follow the browser API hierarchy as closely as possible, so a developer can simply start from "Window." and use IntelliSense to navigate to the desired API.
In other words, I wanted to avoid a situation where developers first need to figure out which service should be injected. Discoverability is actually one of the strongest motivations behind this proposal.
Regarding NavigationManager, I agree that it is not a 1-to-1 mapping of a browser API. However, I see it as a special case because it is deeply connected to Blazor routing and was not originally designed as a direct browser API wrapper. For that reason, I am not sure it should define the direction for all browser platform APIs.
Another interesting point is maintainability. If the API structure follows WebIDL closely, we may be able to use WebIDL metadata in the future to generate or extend browser API support by AI agents. This is still only an idea, but I think it is worth exploring as we consider the long-term maintenance cost of a large API surface.
Another reason is trimming and extensibility. If every browser API family becomes its own service, we may eventually end up with many registrations. The current design keeps unused APIs trimmable and is built on an extension mechanism.
Another interesting aspect of this approach is that it may eventually allow the community to add support for additional browser APIs without waiting for Microsoft to ship them. Storage is already implemented on top of that mechanism. Whether such an extension point should become public is still an open question, but the architecture is intentionally moving in that direction. If we can make that work safely, developers could extend the browser API surface while preserving the same discovery experience from "Window.".
So the main goals behind this proposal are
I completely agree that the more .NET-style approach can provide a great developer experience too. My proposal is simply making a different set of trade-offs. It gives up some .NET idioms in favor of the goals above.
I don't insist that this design is the only correct answer. Like any API design, it is a series of trade-offs. But at this point, I would still prefer to keep the proposal moving in this direction.
As for ValueTask, I will share my thoughts on that separately.
jsakamotoIGJP commentedon Sep 25, 2026
@KristofferStrube Speaking about the return type of methods in this API proposal, good point.
In this scenario,
ValueTaskdoesn't offer much performance advantage overTask, as you said. Rather,ValueTaskhas some limitations, like it can't be awaited twice.However, I'd like to follow the conventions of the Blazor JS Interop API family. Because those JS Interop APIs that return
ValueTaskhave the potential to improve performance in a Blazor WebAssembly scenario. As you know, we can useIJSInProcessRuntimeto invoke JS functions synchronously on Blazor WebAssembly, which saves memory allocation and improves performance.Unfortunately, the Blazor runtime has never utilized this potential so far. However, if we choose
Taskinstead ofValueTask, that possibility will be gone forever. We should keep in mind that the return type can't change after the API is public.ilonatommy commentedon Sep 29, 2026
@jsakamotoIGJP, thank you for working through this design. I agree that the 1:1 approach covers the goal of this project - to simplify and reduce manual steps for developers.
I want to go back to the ownership question. We would like to keep browser ownership so removing disposal is sound, however I might not understand the problem behind your proposal.
I double checked the "changed proposal" you're quoting and I don't understand how
await using var storage = browser.Window.LocalStorage;can still work. The compiler reports:KristofferStrube commentedon Sep 29, 2026
I forgot another thing.
The thing about not exposing CancellationTokens in the method signatures. It is correct that AbortSignals and CancellationTokens are analogous. But when making JSInterop calls there is still a small benefit to actually parsing one even if the JS method does not need/use one. In the case where the invocation is cancelled then the JSRuntime won’t use time deserializing the result. This can be important in some niche use cases where big payloads are returned from JS but where the retrieval might be cancelled due to some user interaction (like when people implement debounce). I think this is especially relevant for the Web storage section of the HTML API as you can read big strings via the API.
So I think we should think about whether we want to expose a way to parse the token or deliberately keep the API simpler.
It is something I never implemented in my wrappers, but would have liked to in hindsight.
jsakamotoIGJP commentedon Oct 2, 2026
@ilonatommy Sorry, my explanation in the previous comment was not clear.
What I meant is that
Storagestill implementsIAsyncDisposable, butDisposeAsyncis implemented explicitly, so it isn't visible as part of the "public API" specification.In that case,
DisposeAsyncdoes not appear in IntelliSense, but "await using var" is still able to compile.That's what I meant when I said the solution isn't perfect.
I attached a small sample project below to demonstrate the behavior.
Addition: For the current prototype, I made the implementation continue working even if someone intentionally disposes of the object via await using or a cast to IAsyncDisposable, even though I'm not sure whether we should.
2 remaining items
jsakamotoIGJP commentedon Oct 6, 2026
@ilonatommy Sorry for the confusion in my earlier comment.
To be honest, I had thought about an internal async cleanup method before. But I wasn't sure how it would work if we allow community extensions in the future, so I didn't go with it, just in case.
However, your comment made me think about it again, and I'd like to move to an internal disposal mechanism.
Specifically,
Window,Storage, and other features in the future will no longer implementIAsyncDisposable. Instead, I'll add the following interface as internal to this assembly, and each feature will implement it explicitly when it needs cleanup.With this, no dispose method shows up in IntelliSense, and
await usingno longer be able to compile.If this looks good, please let me know, and I'll update the draft PR (#69305).
ilonatommy commentedon Oct 6, 2026
It does look good to me. Thanks!
jsakamotoIGJP commentedon Oct 7, 2026
@ilonatommy Thank you for confirming!
I updated the issue description to the final API shape.
WindowandStorageno longer implementIAsyncDisposable, and I added short notes about disposal andCancellationToken. I also made the usage example more complete.I also updated #69305 with all the changes we discussed.
WindowandStoragenow use the internalIInternalAsyncDisposalinstead ofIAsyncDisposable.SKILL.mdis removed from the PR.In addition, I fixed one issue I found while reviewing the tests. If getting the storage reference failed or timed out, the failed result stayed cached, and
Storagekept failing for the rest of the scope. Now it tries again on the next call.