Skip to content

Add event listeners to Microsoft.AspNetCore.Components.Platform - #70340

Merged
ilonatommy merged 18 commits into
dotnet:mainfrom
jsakamotoIGJP:components-platform-js-bridge
Nov 9, 2026
Merged

ilonatommy merged 18 commits into
dotnet:mainfrom
jsakamotoIGJP:components-platform-js-bridge

Conversation

@jsakamotoIGJP

@jsakamotoIGJP jsakamotoIGJP commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor
  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Add AddEventListenerAsync with typed event keys to Components.Platform

Description

This PR implements the Events API Proposal Issue (#69922). It adds AddEventListenerAsync to Window and CookieStore, with the first two events, Window.StorageEvent and CookieStore.ChangeEvent. The public API is the one in the proposal, and I followed Ilona's answers to its open questions. This text explains the implementation.

How a listener gets from the browser to .NET

  • One JS module. js/Platform.ts exports createCallback(callbackReference, shapesJson). It is bundled by rollup and shipped as a static web asset, so the project is now Microsoft.NET.Sdk.Razor. The module has no family-specific code, and it is 397 bytes after Brotli. It is imported once per scope, when the first listener is added.
  • Shapes. An event object cannot cross to .NET as it is. Each event key carries a JSON shape that names the properties to copy. Plain objects, arrays, and primitives are copied. Any other object becomes a marker, {"__unsupported":"<type name>"}, because a reference created in JS would have no owner to dispose it.
  • Event keys. EventType<TTarget, TEvent> holds the event name and how to add a listener. The key is created by an internal helper that knows the event object type, so the public AddEventListenerAsync methods need no trimming annotations. A key of one target does not compile on another.
  • Registrations. Each call creates an EventListener<TEvent>. It owns the JS function and the DotNetObjectReference, and it is the IAsyncDisposable that the caller gets. Disposing it, or canceling its token, removes the listener. After that, no new call to the listener starts, even if a call was already on its way in Interactive Server.
  • Scope end. EventListenerCollection tracks the live registrations, so disposing the scope removes the ones the app did not. Window and CookieStore each have one, created by FeatureContext (Pass a FeatureContext to Components.Platform feature factories #69993). FeatureContext also holds the module loader, which is shared by the scope and disposed last. Window creates its collection when the first listener is added, so an app that adds no listener pays nothing. The fields that hold them are typed as IInternalAsyncDisposal, so in a trimmed app that adds no listener, no event type is left.
  • Errors. An exception from a listener is logged at Error level through ILoggerFactory, and the listener stays added. BrowserPlatform takes an optional ILoggerFactory and falls back to NullLoggerFactory.

Things worth a look

  • Cancellation. The token overload removes the listener when the token is canceled. The removal is posted to the captured SynchronizationContext by hand. useSynchronizationContext: true is not used, because its Send blocks forever when Cancel runs on Blazor's renderer context. A test hung on this.
  • Renderer context. Adding a listener changes unlocked state, so the awaits in AddEventListenerAsync keep the renderer's synchronization context. A unit test checks that for Window and CookieStore.
  • Package changes. The root package.json and package-lock.json get one workspace line each for src/Components/Platform/src/js, like the other JS projects. Microsoft.Extensions.Logging.Abstractions comes from the existing references.
  • Cost on Interactive Server. Each event is one call from JS to .NET, which is a network message. That is fine for these two events, because they are rare.
  • Not in this PR. There is no ForEachAsync helper, as discussed on the proposal.

Tests

  • Unit tests (78 in the Platform test project in total) cover the callback bridge, the listener lifecycle (add, remove, cancel before, during, and after the addition, scope end, a failing removal), logging of listener exceptions, and the public API rules.
  • Jest tests (8) cover Platform.ts.
  • E2E tests watch storage events fired by another page, and change events of the cookie store, in Interactive Server and WebAssembly. A third E2E test uses a test-only key for the message event of window (InternalsVisibleTo for the test app, no public API). It posts nested JSON values and values that are not JSON (Date, Map) with window.postMessage, and checks that a JsonElement receives them, with markers in place of the non-JSON values.
  • I ran the unit and E2E tests locally, from the build output and from the output of dotnet publish. I also published a small WebAssembly app with trimming, once with a listener and once without. Without a listener, no event type is left in the assembly.

Contributes to #69922
Contributes to #69987

- Add a JS module (src/js/Platform.ts) with one export, createCallback. It
  returns a function that forwards any number of arguments to a .NET
  JSCallback. Each argument has a shape that selects what is copied, so an
  event can cross by value. Ship it as a static web asset, as
  Server.AutoPause does.
- Add JSCallback<T1>, <T1,T2>, <T1,T2,T3> and JSCallbackFactory.
- Add CookieStore.SetOnChangeAsync and CookieChangeEvent as the first user.
- Add jest, unit, and E2E tests.

This is a local trial and not part of the Cookie Store PR.
… key

- Add EventType<TTarget, TEvent>. CookieStore.ChangeEvent is the first key,
  and CookieStore.AddEventListenerAsync takes it. A key of another target
  does not compile.
- Each call adds its own listener and returns an IAsyncDisposable that
  removes it. Scope disposal removes every listener that is still added.
- Log an exception from a listener at Error level, so it does not get lost
  in the browser console.
- The bridge no longer turns an unexpected browser object into a JS object
  reference that nobody disposes. It sends {"__unsupported": "<type>"}.
- Share one JSCallbackFactory per Window. Each listener owns its function
  and DotNetObjectReference.
- Add Window.AddEventListenerAsync and the key Window.StorageEvent, a
  static extension member in WindowWebStorageExtensions.
- StorageEvent.StorageArea is the existing LocalStorage or SessionStorage
  instance. A new { $known: [...] } shape sends the name of the matching
  global, such as "localStorage", instead of a reference.
- An EventType can convert the payload before the listener gets it, so the
  public event type can refer to existing projections.
- The E2E test changes localStorage in a second page of the same browser
  context, because the event does not fire in the page that made the change.
Name the JSCallbackFactory parameters and fields callbackFactory, not
callbacks, which read as a collection of callbacks. Name the
DotNetObjectReference that a created function calls callbackReference,
not target, which clashed with the event target in EventListener.
Drop the Logging.Abstractions package reference, which the SDK now prunes (NU1510),
and report the event demo steps through the result marker of the Cookie Store page.
Keep the renderer's synchronization context while adding and removing listeners,
because their state is not locked. Release the function and the callback reference
even when removeEventListener fails, and let scope disposal continue with the other
listeners and log the failure. Release a module that arrives after disposal and
stop before createCallback.

BrowserJSRuntime can now complete calls on the thread pool and fail or hold a call,
which the new EventListenerLifecycleTest relies on.
AddEventListenerAsync on Window and CookieStore takes an optional
CancellationToken, the .NET form of the signal option of addEventListener.
Canceling it removes the listener at any time: before the call nothing is
added, during the addition the listener is removed when the addition ends
and the call throws OperationCanceledException with the token, and after it
the listener is removed as disposing the handle does. A component can then
pass a token that it cancels in Dispose, and needs no handle.

The token callback posts the removal to the context that added the listener
itself. useSynchronizationContext: true would call Send, which blocks forever
when Cancel runs on the renderer's own context.

The second listener of the Cookie Store demo now uses a token.
AddEventListenerAsync on Window and CookieStore now has an overload without
a token and one with a required token, as the package maps other optional
parameters. An optional token would conflict with RS0026 and RS0027 when an
overload for AddEventListenerOptions such as once is added later.
…arts on first use

The XML docs of AddEventListenerAsync on Window and CookieStore now say that each call creates its own registration.

Window creates the JS callback factory and its listener collection when the first listener is added, so an app that adds no listener pays nothing.
@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label Nov 6, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @jsakamotoIGJP. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

Window held them in fields of their own types, so disposal kept the types. Typing the fields as IInternalAsyncDisposal lets the trimmer remove them.
…or interop

A test-only key for the window message event (made with the internal EventTypes helper, so the test app gets InternalsVisibleTo) shows that nested JSON values and markers for Date and Map arrive in both render modes.
@jsakamotoIGJP
jsakamotoIGJP marked this pull request as ready for review November 6, 2026 04:35
@jsakamotoIGJP
jsakamotoIGJP requested review from a team and wtgodbe as code owners November 6, 2026 04:35
Copilot AI balanced review requested due to automatic review settings November 6, 2026 04:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical build-output tracking and disposal-cleanup gaps can leave packages without the event bridge and CookieStore listeners active after disposal fails.

4 open issues
What changed in this PR

Adds typed browser event listeners to Microsoft.AspNetCore.Components.Platform, implementing the event pattern proposed in #69922 and supporting reactive browser APIs tracked by #69987.

Changes:

  • Adds typed event keys and listener registration for Window storage events and Cookie Store changes.
  • Introduces a JavaScript callback bridge with cancellation, disposal, and exception logging.
  • Adds unit, JavaScript, and browser tests, plus packaging for the JavaScript module.
File Description
src/​Components/​Platform/​testassets/​PlatformTestApp/​Components/​Pages/​MessageEventServer.razor Hosts the Server message-event demo.
src/​Components/​Platform/​testassets/​PlatformTestApp.E2E.Tests/​Tests/​StorageTests.cs Tests cross-page storage notifications.
src/​Components/​Platform/​testassets/​PlatformTestApp.E2E.Tests/​Tests/​MessageEventTests.cs Tests JSON payloads and unsupported-value markers.
src/​Components/​Platform/​testassets/​PlatformTestApp.E2E.Tests/​Tests/​CookieStoreTests.cs Tests independent listeners, removal, and cancellation.
src/​Components/​Platform/​testassets/​PlatformTestApp.Client/​Pages/​MessageEventWebAssembly.razor Hosts the WebAssembly message-event demo.
src/​Components/​Platform/​testassets/​PlatformTestApp.Client/​Components/​StorageDemo.razor Displays storage events and storage identity.
src/​Components/​Platform/​testassets/​PlatformTestApp.Client/​Components/​MessageEventDemo.razor Exercises a test-only message-event key.
src/​Components/​Platform/​testassets/​PlatformTestApp.Client/​Components/​CookieStoreDemo.razor Adds cookie listener controls and event displays.
src/​Components/​Platform/​test/​StorageTest.cs Tests event conversion and scope cleanup.
src/​Components/​Platform/​test/​RecordingLoggerFactory.cs Captures listener logs for assertions.
src/​Components/​Platform/​test/​PublicApiTest.cs Includes Window in asynchronous API checks.
src/​Components/​Platform/​test/​Microsoft.AspNetCore.Components.Platform.Tests.csproj Adds the Components dependency for dispatcher tests.
src/​Components/​Platform/​test/​JSCallbackTest.cs Tests callback creation, invocation, and ownership.
src/​Components/​Platform/​test/​EventListenerLifecycleTest.cs Tests cancellation, disposal, failures, and context preservation.
src/​Components/​Platform/​test/​CookieStoreTest.cs Tests listener delivery, independence, and logging.
src/​Components/​Platform/​test/​BrowserJSRuntime.cs Provides controllable interop responses for tests.
src/​Components/​Platform/​src/​WindowWebStorageExtensions.cs Exposes the typed storage-event key.
src/​Components/​Platform/​src/​WindowCookieStoreExtensions.cs Supplies CookieStore listener infrastructure.
src/​Components/​Platform/​src/​Window.cs Adds listener registration and scope-owned resources.
src/​Components/​Platform/​src/​StorageEventPayload.cs Maps storage names to existing projections.
src/​Components/​Platform/​src/​StorageEvent.cs Defines the public storage-event payload.
src/​Components/​Platform/​src/​PublicAPI.Unshipped.txt Records the new public event APIs.
src/​Components/​Platform/​src/​Microsoft.AspNetCore.Components.Platform.csproj Packages the JavaScript module as a static web asset.
src/​Components/​Platform/​src/​JSCallbackFactory.cs Imports the module and creates callback references.
src/​Components/​Platform/​src/​JSCallback.cs Defines invokable typed callback adapters.
src/​Components/​Platform/​src/​js/​tsconfig.json Configures TypeScript compilation.
src/​Components/​Platform/​src/​js/​test/​Platform.test.ts Tests callback forwarding and payload conversion.
src/​Components/​Platform/​src/​js/​rollup.config.mjs Builds the bridge as an ES module.
src/​Components/​Platform/​src/​js/​Platform.ts Converts browser payloads and invokes .NET callbacks.
src/​Components/​Platform/​src/​js/​package.json Defines bridge build and test scripts.
src/​Components/​Platform/​src/​js/​jest.config.js Configures JavaScript tests and reporting.
src/​Components/​Platform/​src/​js/​dist/​.gitignore Excludes generated bundle artifacts.
src/​Components/​Platform/​src/​js/​babel.config.js Configures TypeScript transformation for tests.
src/​Components/​Platform/​src/​EventType.cs Defines typed event keys and internal factories.
src/​Components/​Platform/​src/​EventListenerCollection.cs Tracks registrations and coordinates cleanup.
src/​Components/​Platform/​src/​EventListener.cs Implements individual listener lifecycles.
src/​Components/​Platform/​src/​CookieStore.cs Adds change-event registration and cleanup.
src/​Components/​Platform/​src/​CookieChangeEvent.cs Defines changed and deleted cookie lists.
src/​Components/​Platform/​src/​BrowserPlatform.cs Supplies optional logging infrastructure.
package.json Registers the Platform JavaScript workspace.
package-lock.json Records the workspace and package link.

Review effort: Balanced

Comment thread package.json Resolved
Comment thread src/Components/Platform/src/Window.cs Resolved
@PureWeen

PureWeen commented Nov 6, 2026

Copy link
Copy Markdown
Member

/review

@ilonatommy
ilonatommy self-requested a review November 6, 2026 08:01
@ilonatommy ilonatommy added the feature-blazor-jsinterop This issue is related to JSInterop in Blazor label Nov 6, 2026

@PureWeen PureWeen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The unrelated src/submodules/googletest pointer change is the only finding retained for this review. Please restore the main pointer.

Review scope

The three-arm local panel (G, S, O) reviewed commit 621bf279c3d882d691310044ca814aa4f924c2d5.
Hosted /review run 42168488718 reviewed that same commit.
The hosted run completed with an explicit safe-output noop after it removed findings already covered by existing feedback.

This review is anchored to ead6ef6bdafa1090c25f92b72cf95ab31f3b959b.
I verified the complete two-commit +8/-0 delta from the reviewed commit:

  • d4324bc59ed11283ceeeef1ff16c7cd16088f58d adds the three Platform JS output paths to eng/Npm.Workspace.nodeproj: the Debug bundle, Debug source map, and Release bundle.
  • ead6ef6bdafa1090c25f92b72cf95ab31f3b959b adds ObjectDisposedException.ThrowIf(_disposed, this); at src/Components/Platform/src/EventListenerCollection.cs:70.

This delta check is not a new full-panel review of the final head.

Earlier CCR feedback

Comment Status
4489112077 Fixed in d4324bc59e. The three JS output paths are now present.
4489112184 Fixed in ead6ef6bda. The disposal check now precedes cancellation registration.
4489112121 The author declined this change in 4489969683. Their rationale cites circuit-disconnect ordering and JSObjectReference.DisposeAsync handling JSDisconnectedException.
4489112143 The author declined this change in 4490193139. They prefer the acquisition failure, including NotSupportedException, over cancellation translation when the API is unavailable.

All four threads are resolved. This review does not reopen them or repeat their inline comments.

Non-blocking trace notes

The following statement applies to each note below:

Posted for informational purposes so the author can confirm the verifier didn't discard or leave unresolved a real finding; this item does not block agent-reviewed-approved.

  • G-U1, BrowserPlatform.cs:4 [UNRESOLVED]: The logging-reference concern lacks evaluated dependency and package evidence. It does not establish a missing compile reference or package dependency defect.
  • G-C1, EventListenerLifecycleTest.cs:260 [DISCARDED]: The helper parameter has type ILoggerFactory?. AddSingleton(loggerFactory) therefore registers the interface, not only the concrete logger factory.
  • O-U1, CookieChangeEvent.cs:17 [UNRESOLVED]: The deleted-cookie Value documentation needs confirmation against the Cookie Store specification or browser behavior. This review does not assert a documentation defect.
  • S-WINDOW-LATE-REFERENCE, Window.cs:88: Only S raised this late-acquisition lifetime claim. Another arm identified analogous pre-existing acquisition behavior. No executed reproduction establishes the claimed new retained reference. The user-directed follow-up did not retain this claim as a blocking inline comment.
  • O-CALLBACK-UNHANDLED-REJECTION, Platform.ts:22: Only O raised this circuit-disposal callback claim. Its proposed trigger concerns listeners that rely solely on scope disposal. Existing demos dispose or cancel their listeners, and no browser reproduction establishes the proposed failure. The user-directed follow-up did not retain this claim as a blocking inline comment.

Human-directed and GitHub Copilot-generated.

Comment thread src/submodules/googletest Resolved
@jsakamotoIGJP

Copy link
Copy Markdown
Contributor Author

@ilonatommy I addressed your comments in ed515f8, and the googletest pointer that PureWeen pointed out in 470c2dd. Could you take another look and approve it again?

One CI check failed, "Monitor Helix Jobs" in aspnetcore-ci. It does not look related to this PR. The monitor stopped when Azure DevOps returned 503, and before that the SignalR Java client tests failed because the Gradle download returned 504. I don't seem to have permission to rerun it (please let me know if I'm wrong). Could you also rerun the failed check?

@ilonatommy
ilonatommy merged commit eaa04f5 into dotnet:main Nov 9, 2026
33 checks passed
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 50%

No docs PR was created. This is "insufficient evidence" rather than "no docs needed". The PR adds public event-listener APIs to the unshipped Components.Platform package, and no existing documentation covers that package. Human review is recommended to decide where the docs should live.

Documentation surfaces considered

  • Conceptual article: Not required — New public API (PublicAPI.Unshipped.txt) in the Components.Platform package, but the docs repo has no article covering that package, and the API is unshipped. Evidence is insufficient to draft an article for this increment alone. Human review is recommended once the package docs are planned.
  • Migration guidance: Not required — The new API is additive, so users have no upgrade action.
  • Breaking change: Not required — No removed APIs or changed defaults. The change only adds new, unshipped APIs.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — be1b24f7 Deployed Nov 9, 2026 by ilonatommy via conclusion #242
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-reviewed-needs-changes area-blazor Includes: Blazor, Razor Components community-contribution Indicates that the PR has been added by a community member feature-blazor-jsinterop This issue is related to JSInterop in Blazor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants