Guard against null object when trying to fetch a function

This commit is contained in:
Karl Seguin
2025-06-02 23:27:29 +08:00
parent 1ac23ce191
commit 167fe5f758
2 changed files with 14 additions and 0 deletions

View File

@@ -222,4 +222,10 @@ test "Browser.DOM.EventTarget" {
.{ "content.dispatchEvent(new Event('he'));", null }, .{ "content.dispatchEvent(new Event('he'));", null },
.{ "obj1.calls", "1" }, .{ "obj1.calls", "1" },
}, .{}); }, .{});
// doesn't crash on null receiver
try runner.testCases(&.{
.{ "content.addEventListener('he2', null);", null },
.{ "content.dispatchEvent(new Event('he2'));", null },
}, .{});
} }

View File

@@ -1400,7 +1400,11 @@ pub fn Env(comptime State: type, comptime WebApis: type) type {
} }
pub fn getFunction(self: JsObject, name: []const u8) !?Function { pub fn getFunction(self: JsObject, name: []const u8) !?Function {
if (self.isNullOrUndefined()) {
return null;
}
const scope = self.scope; const scope = self.scope;
const js_name = v8.String.initUtf8(scope.isolate, name); const js_name = v8.String.initUtf8(scope.isolate, name);
const js_value = try self.js_obj.getValue(scope.context, js_name.toName()); const js_value = try self.js_obj.getValue(scope.context, js_name.toName());
@@ -1409,6 +1413,10 @@ pub fn Env(comptime State: type, comptime WebApis: type) type {
} }
return try scope.createFunction(js_value); return try scope.createFunction(js_value);
} }
pub fn isNullOrUndefined(self: JsObject) bool {
return self.js_obj.toValue().isNullOrUndefined();
}
}; };
// This only exists so that we know whether a function wants the opaque // This only exists so that we know whether a function wants the opaque