Skip to content

Enable IJSObjectReference to handle null/undefined values #62657

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
merged 8 commits into from
Jul 14, 2025

Conversation

rolandVi
Copy link
Contributor

Enable IJSObjectReference to handle null/undefined values

Problem

Currently, calling DotNet.createJSObjectReference(null) or DotNet.createJSObjectReference(undefined) throws an error: This forces developers to write workaround code when JavaScript functions might return null/undefined values.

Solution

Modified createJSObjectReference to handle null/undefined values by returning a special sentinel object with __jsObjectId: -1 instead of throwing an error. The .NET side JSON converter recognizes this sentinel value and returns null for the IJSObjectReference?.

Changes

  • JavaScript side: createJSObjectReference() now accepts null/undefined and returns {__jsObjectId: -1}
  • .NET side: JSObjectReferenceJsonConverter recognizes the -1 sentinel and returns null
  • Disposal: Updated disposeJSObjectReference() to safely handle null references (skip disposal for id -1)

Benefits

  • Non-breaking change: Converts from exception to success

Fixes #52070

@rolandVi rolandVi requested a review from a team as a code owner July 10, 2025 14:27
@github-actions github-actions bot added the area-blazor Includes: Blazor, Razor Components label Jul 10, 2025
@dotnet-policy-service dotnet-policy-service bot added the community-contribution Indicates that the PR has been added by a community member label Jul 10, 2025
@oroztocil
Copy link
Member

oroztocil commented Jul 10, 2025

Please check that you get an expected result when you do var result = await JS.GetValueAsync<IJSObjectReference>("someProp"); in both cases:

  • When someProp is defined in the scope with value set to null or undefined.
  • When someProp is not defined in the scope.

@ilonatommy ilonatommy added this to the 10.0-preview7 milestone Jul 14, 2025
Copy link
Member

@oroztocil oroztocil left a comment

Choose a reason for hiding this comment

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

Nice! 🚀

@ilonatommy ilonatommy merged commit 36e93fa into dotnet:main Jul 14, 2025
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-blazor Includes: Blazor, Razor Components community-contribution Indicates that the PR has been added by a community member
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Allow JS.InvokeAsync<IJSObjectReference> calls to return null/undefined
4 participants