Repository navigation
Add event listeners to Microsoft.AspNetCore.Components.Platform #70340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ilonatommy
merged 18 commits into
dotnet:main
from
jsakamotoIGJP:components-platform-js-bridge
Nov 9, 2026
+2,080
−10
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
2f21a51
Try a generic JS callback bridge for Components.Platform events
jsakamotoIGJP efdb3da
Replace SetOnChangeAsync with AddEventListenerAsync and a typed event…
jsakamotoIGJP 1527412
Add the storage event on Window with AddEventListenerAsync
jsakamotoIGJP 7b0870e
Rename JS callback bridge identifiers for readability
jsakamotoIGJP 03fa0b7
Adapt the bridge trial to dotnet/main after the rebase
jsakamotoIGJP 65b950b
Fix the lifecycle problems found in the event listener review
jsakamotoIGJP 0342221
Remove event listeners when a CancellationToken is canceled
jsakamotoIGJP 0c4b0ae
Take the CancellationToken in an overload, not as an optional parameter
jsakamotoIGJP f45eecb
Document independent listener registrations and create Window event p…
jsakamotoIGJP f24b0a7
Keep the Window event parts out of trimmed apps that add no listener
jsakamotoIGJP 621bf27
Test that an any-typed event value reaches a JsonElement through Blaz…
jsakamotoIGJP d4324bc
Track the Platform JS bundles as npm build outputs
jsakamotoIGJP ead6ef6
Reject a listener whose addition ends after scope disposal
jsakamotoIGJP 5d7bae3
Remove the unused two- and three-argument JSCallback types
jsakamotoIGJP d614612
Merge remote-tracking branch 'dotnet/main' into components-platform-j…
jsakamotoIGJP 470c2dd
Restore the googletest submodule pointer to main
jsakamotoIGJP ed515f8
Clarify the comments in Platform.ts
jsakamotoIGJP be1b24f
Remove a stale mention of other arities
jsakamotoIGJP File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Platform; | ||
|
|
||
| /// <summary> | ||
| /// Represents a change to the cookies visible to the current page. | ||
| /// </summary> | ||
| public sealed class CookieChangeEvent | ||
| { | ||
| /// <summary> | ||
| /// Gets the cookies that were created or changed. | ||
| /// </summary> | ||
| public IReadOnlyList<CookieListItem> Changed { get; init; } = []; | ||
|
|
||
| /// <summary> | ||
| /// Gets the cookies that were deleted. Their <see cref="CookieListItem.Value"/> is <see langword="null"/>. | ||
| /// </summary> | ||
| public IReadOnlyList<CookieListItem> Deleted { get; init; } = []; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.AspNetCore.Internal; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.JSInterop; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Platform; | ||
|
|
||
| /// <summary> | ||
| /// One listener added with <c>addEventListener</c>. Disposing it or canceling its token removes the listener. | ||
| /// </summary> | ||
| internal sealed class EventListener<[DynamicallyAccessedMembers(LinkerFlags.JsonSerialized)] TEvent> : IAsyncDisposable | ||
| { | ||
| private readonly EventListenerCollection _owner; | ||
| private readonly IJSObjectReference _target; | ||
| private readonly string _type; | ||
| private readonly Func<TEvent, Task> _listener; | ||
| private readonly CancellationToken _cancellationToken; | ||
| private readonly ILogger _logger; | ||
| private IJSObjectReference? _function; | ||
| private IDisposable? _callbackReference; | ||
| private SynchronizationContext? _synchronizationContext; | ||
| private CancellationTokenRegistration _cancellationRegistration; | ||
| private bool _removed; | ||
|
|
||
| public EventListener(EventListenerCollection owner, IJSObjectReference target, string type, Func<TEvent, Task> listener, CancellationToken cancellationToken, ILogger logger) | ||
| { | ||
| _owner = owner; | ||
| _target = target; | ||
| _type = type; | ||
| _listener = listener; | ||
| _cancellationToken = cancellationToken; | ||
| _logger = logger; | ||
| } | ||
|
|
||
| public async Task AddAsync(JSCallbackFactory callbackFactory, string shapesJson) | ||
| { | ||
| var callback = new JSCallback<TEvent> { Handler = InvokeListenerAsync }; | ||
| (_function, _callbackReference) = await callbackFactory.CreateAsync(callback, shapesJson); | ||
|
|
||
| // Disposal can run while the function is being created, and then nothing else releases it. | ||
| if (_removed || _cancellationToken.IsCancellationRequested) | ||
| { | ||
| await ReleaseAsync(); | ||
| _cancellationToken.ThrowIfCancellationRequested(); | ||
| throw new ObjectDisposedException(GetType().Name); | ||
| } | ||
|
|
||
| await _target.InvokeVoidAsync("addEventListener", _type, _function); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Removes the listener when its token is canceled. Call it once the listener is added. | ||
| /// </summary> | ||
| public void RemoveWhenCanceled() | ||
| { | ||
| // Not useSynchronizationContext: its Send blocks forever when Cancel runs on Blazor's renderer context. | ||
| _synchronizationContext = SynchronizationContext.Current; | ||
| _cancellationRegistration = _cancellationToken.Register(static state => ((EventListener<TEvent>)state!).OnCanceled(), this); | ||
| } | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| if (_removed) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| _removed = true; | ||
| _cancellationRegistration.Dispose(); | ||
| _owner.Remove(this); | ||
|
|
||
| await ReleaseAsync(); | ||
| } | ||
|
|
||
| private void OnCanceled() | ||
| { | ||
| // Removal changes unlocked state, so it runs on the context that added the listener. | ||
| if (_synchronizationContext is { } context) | ||
| { | ||
| context.Post(static state => _ = ((EventListener<TEvent>)state!).RemoveAfterCancellationAsync(), this); | ||
| } | ||
| else | ||
| { | ||
| _ = RemoveAfterCancellationAsync(); | ||
| } | ||
| } | ||
|
|
||
| private async Task RemoveAfterCancellationAsync() => await _owner.TryDisposeAsync(this); | ||
|
|
||
| private async Task InvokeListenerAsync(TEvent value) | ||
| { | ||
| // A call that left the browser before removal can still arrive. | ||
| if (_removed || _cancellationToken.IsCancellationRequested) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| await _listener(value); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| EventListenerCollection.Log.ListenerThrew(_logger, _type, ex); | ||
| } | ||
| } | ||
|
|
||
| private async ValueTask ReleaseAsync() | ||
| { | ||
| var function = _function; | ||
| var callbackReference = _callbackReference; | ||
| _function = null; | ||
| _callbackReference = null; | ||
|
|
||
| // A failed removal still releases both references, and then reaches the caller. | ||
| try | ||
| { | ||
| if (function is not null) | ||
| { | ||
| try | ||
| { | ||
| await _target.InvokeVoidAsync("removeEventListener", _type, function); | ||
| } | ||
| catch (JSDisconnectedException) | ||
| { | ||
| // The page is already gone, so nothing can call the listener. | ||
| } | ||
| finally | ||
| { | ||
| await function.DisposeAsync(); | ||
| } | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| callbackReference?.Dispose(); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.