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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ public override bool CanConvert(Type typeToConvert)
public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader);

if (id == -1)
{
return null;
}

return new WebAssemblyJSObjectReference(_jsRuntime, id);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,17 @@ public void Read_ReadsJson_IJSInProcessObjectReference()
// Assert
Assert.Equal(expectedId, deserialized?.Id);
}

[Fact]
public void Read_ReturnsNull_WhenIdIsMinusOne()
{
// Arrange
var json = "{\"__jsObjectId\":-1}";

// Act
var deserialized = JsonSerializer.Deserialize<IJSObjectReference>(json, JsonSerializerOptions);

// Assert
Assert.Null(deserialized);
}
}
18 changes: 12 additions & 6 deletions src/Components/test/E2ETest/Tests/InteropTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,6 @@ public void CanInvokeInteropMethods()
["invokeVoidAsyncReturnsWithoutSerializing"] = "Success",
["invokeVoidAsyncReturnsWithoutSerializingInJSObjectReference"] = "Success",
["invokeAsyncThrowsSerializingCircularStructure"] = "Success",
["invokeAsyncThrowsUndefinedJSObjectReference"] = "Success",
["invokeAsyncThrowsNullJSObjectReference"] = "Success",
["disposeJSObjectReferenceAsync"] = "Success",
// GetValue tests
["getValueFromDataPropertyAsync"] = "10",
Expand All @@ -108,7 +106,12 @@ public void CanInvokeInteropMethods()
["invokeConstructorWithClassConstructorAsync.function"] = "6",
["invokeConstructorWithNonConstructorAsync"] = "Success",
// Function reference tests
["changeFunctionViaObjectReferenceAsync"] = "42"
["changeFunctionViaObjectReferenceAsync"] = "42",
// JS Object Nullable reference tests
["invokeAsyncUndefinedJSObjectReference"] = "Success",
["invokeAsyncNullJSObjectReference"] = "Success",
["invokeAsyncNullFromVariableJSObjectReference"] = "Success",
["invokeAsyncNonExistentJSObjectReference"] = "Success",
};

var expectedSyncValues = new Dictionary<string, string>
Expand Down Expand Up @@ -148,8 +151,6 @@ public void CanInvokeInteropMethods()
["invokeVoidReturnsWithoutSerializingIJSInProcessRuntime"] = "Success",
["invokeVoidReturnsWithoutSerializingInIJSInProcessObjectReference"] = "Success",
["invokeThrowsSerializingCircularStructure"] = "Success",
["invokeThrowsUndefinedJSObjectReference"] = "Success",
["invokeThrowsNullJSObjectReference"] = "Success",
["stringValueUpperSync"] = "MY STRING",
["testDtoNonSerializedValueSync"] = "99999",
["testDtoSync"] = "Same",
Expand All @@ -174,7 +175,12 @@ public void CanInvokeInteropMethods()
["invokeConstructorWithClassConstructor.function"] = "6",
["invokeConstructorWithNonConstructor"] = "Success",
// Function reference tests
["changeFunctionViaObjectReference"] = "42"
["changeFunctionViaObjectReference"] = "42",
// JS Object Nullable reference tests
["invokeUndefinedJSObjectReference"] = "Success",
["invokeNullJSObjectReference"] = "Success",
["invokeNullFromVariableJSObjectReference"] = "Success",
["invokeNonExistentJSObjectReference"] = "Success",
};

// Include the sync assertions only when running under WebAssembly
Expand Down
180 changes: 125 additions & 55 deletions src/Components/test/testassets/BasicTestApp/InteropComponent.razor
Original file line number Diff line number Diff line change
Expand Up @@ -167,33 +167,6 @@
ReturnValues["invokeAsyncThrowsSerializingCircularStructure"] = $"Failure: {ex.Message}";
}

try
{
var undefinedJsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("returnUndefined");
ReturnValues["invokeAsyncThrowsUndefinedJSObjectReference"] = undefinedJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeAsyncThrowsUndefinedJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncThrowsUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
var nullJsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("returnNull");
ReturnValues["invokeAsyncThrowsNullJSObjectReference"] = nullJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeAsyncThrowsNullJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncThrowsNullJSObjectReference"] = $"Failure: {ex.Message}";
}

var jsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("returnJSObjectReference");
ReturnValues["jsObjectReference.identity"] = await jsObjectReference.InvokeAsync<string>("identity", "Invoked from JSObjectReference");
Expand Down Expand Up @@ -308,6 +281,13 @@
FunctionReferenceTests();
}

await JSObjectReferenceAsyncTests();

if (shouldSupportSyncInterop)
{
JSObjectReferenceTests();
}

Invocations = invocations;
DoneWithInterop = true;
}
Expand Down Expand Up @@ -394,34 +374,6 @@
ReturnValues["invokeThrowsSerializingCircularStructure"] = $"Failure: {ex.Message}";
}

try
{
var undefinedJsObjectReference = inProcRuntime.Invoke<IJSObjectReference>("returnUndefined");
ReturnValues["invokeThrowsUndefinedJSObjectReference"] = undefinedJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeThrowsUndefinedJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeThrowsUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
var nullJsObjectReference = inProcRuntime.Invoke<IJSObjectReference>("returnNull");
ReturnValues["invokeThrowsNullJSObjectReference"] = nullJsObjectReference is null ? "Failure: null" : "Failure: not null";
}
catch (JSException)
{
ReturnValues["invokeThrowsNullJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeThrowsNullJSObjectReference"] = $"Failure: {ex.Message}";
}

var jsInProcObjectReference = inProcRuntime.Invoke<IJSInProcessObjectReference>("returnJSObjectReference");
ReturnValues["jsInProcessObjectReference.identity"] = jsInProcObjectReference.Invoke<string>("identity", "Invoked from JSInProcessObjectReference");

Expand Down Expand Up @@ -626,6 +578,124 @@
ReturnValues["changeFunctionViaObjectReference"] = testClassRef.Invoke<int>("getTextLength").ToString();
}

private async Task JSObjectReferenceAsyncTests()
{
try
{
var undefinedJsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("jsInteropTests.returnUndefined");
ReturnValues["invokeAsyncUndefinedJSObjectReference"] = undefinedJsObjectReference is null ? "Success" : $"Failure: not null (type: {undefinedJsObjectReference.GetType().FullName})";
}
catch (JSException ex)
{
ReturnValues["invokeAsyncUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
var nullJsObjectReference = await JSRuntime.InvokeAsync<IJSObjectReference>("jsInteropTests.returnNull");
ReturnValues["invokeAsyncNullJSObjectReference"] = nullJsObjectReference is null ? "Success" : $"Failure: not null (type: {nullJsObjectReference.GetType().FullName})";
}
catch (JSException ex)
{
ReturnValues["invokeAsyncNullJSObjectReference"] = $"Failure: {ex.Message}";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncNullJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
var nullVariableJsObjectReference = await JSRuntime.GetValueAsync<IJSObjectReference>("jsInteropTests.testObject.nullProperty");
ReturnValues["invokeAsyncNullFromVariableJSObjectReference"] = nullVariableJsObjectReference is null ? "Success" : $"Failure: not null (type: {nullVariableJsObjectReference.GetType().FullName})";
}
catch (JSException ex)
{
ReturnValues["invokeAsyncNullFromVariableJSObjectReference"] = $"Failure: {ex.Message}";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncNullFromVariableJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
await JSRuntime.GetValueAsync<IJSObjectReference>("nonexistend");
}
catch (JSException)
{
ReturnValues["invokeAsyncNonExistentJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeAsyncNonExistentJSObjectReference"] = $"Failure: {ex.Message}";
}
}

private void JSObjectReferenceTests()
{
var inProcRuntime = ((IJSInProcessRuntime)JSRuntime);

try
{
var undefinedJsObjectReference = inProcRuntime.Invoke<IJSObjectReference>("returnUndefined");
ReturnValues["invokeUndefinedJSObjectReference"] = undefinedJsObjectReference is null ? "Success" : $"Failure: not null (type: {undefinedJsObjectReference.GetType().FullName})";
}
catch (JSException ex)
{
ReturnValues["invokeUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}
catch (Exception ex)
{
ReturnValues["invokeUndefinedJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
var nullJsObjectReference = inProcRuntime.Invoke<IJSObjectReference>("returnNull");
ReturnValues["invokeNullJSObjectReference"] = nullJsObjectReference is null ? "Success" : $"Failure: not null (type: {nullJsObjectReference.GetType().FullName})";
}
catch (JSException ex)
{
ReturnValues["invokeNullJSObjectReference"] = $"Failure: {ex.Message}";
}
catch (Exception ex)
{
ReturnValues["invokeNullJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
var nullVariableJsObjectReference = inProcRuntime.GetValue<IJSObjectReference>("jsInteropTests.testObject.nullProperty");
ReturnValues["invokeNullFromVariableJSObjectReference"] = nullVariableJsObjectReference is null ? "Success" : $"Failure: not null (type: {nullVariableJsObjectReference.GetType().FullName})";
}
catch (JSException ex)
{
ReturnValues["invokeNullFromVariableJSObjectReference"] = $"Failure: {ex.Message}";
}
catch (Exception ex)
{
ReturnValues["invokeNullFromVariableJSObjectReference"] = $"Failure: {ex.Message}";
}

try
{
inProcRuntime.GetValue<IJSObjectReference>("nonexistend");
}
catch (JSException)
{
ReturnValues["invokeNonExistentJSObjectReference"] = "Success";
}
catch (Exception ex)
{
ReturnValues["invokeNonExistentJSObjectReference"] = $"Failure: {ex.Message}";
}
}

public class PassDotNetObjectByRefArgs
{
public string StringValue { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,8 @@ const testObject = {
},
set setOnlyProperty(value) {
this.num = value;
}
},
nullProperty: null
}

window.jsInteropTests = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ export module DotNet {
* @throws Error if the given value is not an Object.
*/
export function createJSObjectReference(jsObject: any): any {
if (jsObject === null || jsObject === undefined) {
return {
[jsObjectIdKey]: -1
};
}

if (jsObject && (typeof jsObject === "object" || jsObject instanceof Function)) {
cachedJSObjectsById[nextJsObjectId] = new JSObject(jsObject);

Expand Down Expand Up @@ -220,7 +226,7 @@ export module DotNet {
export function disposeJSObjectReference(jsObjectReference: any): void {
const id = jsObjectReference && jsObjectReference[jsObjectIdKey];

if (typeof id === "number") {
if (typeof id === "number" && id !== -1) {
disposeJSObjectReferenceById(id);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,55 @@ describe("CallDispatcher", () => {

expect(result2).toBe("30");
});

test("createJSObjectReference: Handles null values without throwing", () => {
const nullRef = DotNet.createJSObjectReference(null);
expect(nullRef).toEqual({ [jsObjectId]: -1 });
});

test("createJSObjectReference: Handles undefined values without throwing", () => {
const undefinedRef = DotNet.createJSObjectReference(undefined);
expect(undefinedRef).toEqual({ [jsObjectId]: -1 });
});

test("disposeJSObjectReference: Safely handles null reference disposal", () => {
const nullRef = DotNet.createJSObjectReference(null);
expect(() => DotNet.disposeJSObjectReference(nullRef)).not.toThrow();
});

test("createJSObjectReference: Still throws for invalid types", () => {
expect(() => DotNet.createJSObjectReference("string")).toThrow();
expect(() => DotNet.createJSObjectReference(123)).toThrow();
expect(() => DotNet.createJSObjectReference(true)).toThrow();
});

test("GetValue: Returns JSObjectReference with sentinel value for null property", () => {
const testObject = { nullProp: null };
const objectId = getObjectReferenceId(testObject);

const result = dispatcher.invokeJSFromDotNet(
"nullProp",
"[]",
DotNet.JSCallResultType.JSObjectReference,
objectId,
DotNet.JSCallType.GetValue
);

expect(result).toBe('{"__jsObjectId":-1}');
});

test("GetValue: Returns JSObjectReference with sentinel value for undefined property", () => {
const testObject = { undefinedProp: undefined };
const objectId = getObjectReferenceId(testObject);

const result = dispatcher.invokeJSFromDotNet(
"undefinedProp",
"[]",
DotNet.JSCallResultType.JSObjectReference,
objectId,
DotNet.JSCallType.GetValue
);

expect(result).toBe('{"__jsObjectId":-1}');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ public override bool CanConvert(Type typeToConvert)
public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader);

if (id == -1)
{
return null;
}

return new JSObjectReference(_jsRuntime, id);
}

Expand Down
Loading
Loading