Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: report exceptions from timers, animation frames and on* handlers

Navid EMAD6ba19824b827
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zig
index f392b9df6..2c438e399 100644
--- a/src/browser/EventManager.zig
+++ b/src/browser/EventManager.zig
@@ -334,15 +334,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {
// Inline handlers (e.g. onclick property) follow the same "report,
// don't propagate" rule as addEventListener listeners — see Listener.run.
- var caught: js.TryCatch.Caught = .{};
- const handler_return: ?js.Value = ls.toLocal(inline_handler).tryCallWithThis(js.Value, target_et, .{event}, &caught) catch |err| ret: {
- if (err == error.ExecutionTerminated) {
- return error.ExecutionTerminated;
- }
- frame.page.recordJsError(err);
- log.debug(.event, "inline handler", .{ .err = err, .caught = caught });
- break :ret null;
- };
+ const handler_return = try callInlineHandler(frame, &ls.local, inline_handler, target_et, event);
processHandlerReturnValue(event, handler_return);
if (adjusted) |a| {
@@ -395,15 +387,7 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event) !void {
const adjusted: ?AdjustedTargets = if (event._needs_retargeting) .apply(event, current_target) else null;
- var caught: js.TryCatch.Caught = .{};
- const handler_return: ?js.Value = ls.toLocal(inline_handler).tryCallWithThis(js.Value, current_target, .{event}, &caught) catch |err| ret: {
- if (err == error.ExecutionTerminated) {
- return error.ExecutionTerminated;
- }
- frame.page.recordJsError(err);
- log.debug(.event, "inline handler", .{ .err = err, .caught = caught });
- break :ret null;
- };
+ const handler_return = try callInlineHandler(frame, &ls.local, inline_handler, current_target, event);
processHandlerReturnValue(event, handler_return);
if (adjusted) |a| {
@@ -470,6 +454,34 @@ fn legacyType(event: *const Event) ?lp.String {
return null;
}
+// Calls an inline handler (onclick attribute or property). An exception it
+// doesn't catch is reported to the window — its "error" event and onerror
+// fire, as for an addEventListener listener (Listener.run) — and dispatch
+// carries on.
+fn callInlineHandler(frame: *Frame, local: *const js.Local, handler: js.Function.Global, this: *EventTarget, event: *Event) error{ExecutionTerminated}!?js.Value {
+ var try_catch: js.TryCatch = undefined;
+ try_catch.init(local);
+ defer try_catch.deinit();
+
+ return local.toLocal(handler).callWithThisRethrow(js.Value, this, .{event}) catch |err| {
+ if (err == error.ExecutionTerminated) {
+ return error.ExecutionTerminated;
+ }
+ if (err == error.JsException or err == error.TryCatchRethrow) {
+ if (try_catch.exceptionValue()) |exc| {
+ // reportError also counts the error on the page.
+ frame.window.reportError(exc, frame) catch |report_err| {
+ log.debug(.event, "inline handler report error", .{ .err = report_err });
+ };
+ return null;
+ }
+ }
+ frame.page.recordJsError(err);
+ log.debug(.event, "inline handler", .{ .err = err });
+ return null;
+ };
+}
+
fn processHandlerReturnValue(event: *Event, handler_return: ?js.Value) void {
const ret = handler_return orelse return;
if (ret.isFalse() and !event._type_string.eql(comptime .wrap("error"))) {
diff --git a/src/browser/EventManagerBase.zig b/src/browser/EventManagerBase.zig
index f15d26646..15823f048 100644
--- a/src/browser/EventManagerBase.zig
+++ b/src/browser/EventManagerBase.zig
@@ -308,17 +308,21 @@ pub fn dispatchDirect(
// Call the property handler (e.g., onmessage) if present
if (getFunction(handler, &ls.local)) |func| {
event._current_target = target;
- var caught: js.TryCatch.Caught = .{};
- _ = func.tryCallWithThis(void, target, .{event}, &caught) catch |err| {
- if (err == error.ExecutionTerminated) {
- return error.ExecutionTerminated;
- }
- page.recordJsError(err);
- if (err == error.JsException) {
+ // Reported like an exception from an addEventListener listener (see
+ // Listener.run), so the global's "error" event / onerror fires.
+ var try_catch: js.TryCatch = undefined;
+ try_catch.init(&ls.local);
+ defer try_catch.deinit();
+ func.callWithThisRethrow(void, target, .{event}) catch |err| switch (err) {
+ error.ExecutionTerminated => return error.ExecutionTerminated,
+ error.JsException, error.TryCatchRethrow => {
event._listeners_did_throw = true;
- } else {
- log.debug(.event, opts.context, .{ .err = err, .caught = caught });
- }
+ Listener.reportException(&try_catch, &ls.local);
+ },
+ else => {
+ page.recordJsError(err);
+ log.debug(.event, opts.context, .{ .err = err });
+ },
};
}
diff --git a/src/browser/global_scope.zig b/src/browser/global_scope.zig
index 21b752494..9e7975ebd 100644
--- a/src/browser/global_scope.zig
+++ b/src/browser/global_scope.zig
@@ -100,6 +100,15 @@ pub const GlobalScope = union(enum) {
};
}
+ // HTML "report an exception": fires the global's "error" event (and its
+ // onerror handler) for an exception no script caught.
+ pub fn reportError(self: GlobalScope, err: JS.Value) !void {
+ return switch (self) {
+ .frame => |frame| frame.window.reportError(err, frame),
+ .worker => |worker| worker.reportError(err),
+ };
+ }
+
pub fn referrerSource(self: GlobalScope) [:0]const u8 {
return switch (self) {
.frame => |frame| frame.referrerSource(),
diff --git a/src/browser/tests/event/report_error.html b/src/browser/tests/event/report_error.html
index 353dc29ec..d2aaa13dc 100644
--- a/src/browser/tests/event/report_error.html
+++ b/src/browser/tests/event/report_error.html
@@ -36,3 +36,50 @@
testing.expectEqual(true, listenerCalled);
window.onerror = null;
</script>
+
+<!--
+ An exception a callback doesn't catch is reported to the global — window's
+ "error" event fires with the thrown value — whatever kind of callback threw:
+ timers, animation frames, inline on* handlers (attribute or property), and
+ property handlers dispatched directly (window.onmessage).
+ https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception
+-->
+<button id=inlineAttrThrower onclick="throw new Error('cb-inline-attribute')"></button>
+<button id=inlinePropThrower></button>
+<script id=reportsCallbackExceptions>
+ testing.async().then((state) => {
+ const seen = [];
+ const thrown = {};
+ const onError = (e) => {
+ const msg = e.error && e.error.message;
+ if (typeof msg === 'string' && msg.startsWith('cb-')) {
+ seen.push(msg);
+ thrown[msg] = e.error instanceof Error;
+ }
+ };
+ window.addEventListener('error', onError);
+
+ setTimeout(() => { throw new Error('cb-setTimeout'); }, 0);
+ const iv = setInterval(() => { clearInterval(iv); throw new Error('cb-setInterval'); }, 0);
+ requestAnimationFrame(() => { throw new Error('cb-requestAnimationFrame'); });
+ document.getElementById('inlinePropThrower').onclick = () => { throw new Error('cb-inline-property'); };
+ window.onmessage = () => { throw new Error('cb-onmessage'); };
+ setTimeout(() => {
+ document.getElementById('inlineAttrThrower').click();
+ document.getElementById('inlinePropThrower').click();
+ window.postMessage('x', '*');
+ }, 0);
+
+ setTimeout(() => state.resolve(), 100);
+
+ state.done(() => {
+ window.removeEventListener('error', onError);
+ window.onmessage = null;
+ testing.expectEqual(
+ 'cb-inline-attribute,cb-inline-property,cb-onmessage,cb-requestAnimationFrame,cb-setInterval,cb-setTimeout',
+ seen.slice().sort().join(','),
+ );
+ for (const msg of seen) testing.expectEqual(true, thrown[msg]);
+ });
+ });
+</script>
diff --git a/src/browser/webapi/Timers.zig b/src/browser/webapi/Timers.zig
index 4058d9d90..3ce67f8aa 100644
--- a/src/browser/webapi/Timers.zig
+++ b/src/browser/webapi/Timers.zig
@@ -219,6 +219,30 @@ const ScheduleCallback = struct {
self.arena.release();
}
+ // An exception the callback doesn't catch is reported to the global, so
+ // window's "error" event and onerror see it — the "report an exception"
+ // step of the timer initialization steps and of running animation frame
+ // and idle callbacks.
+ fn invoke(self: *ScheduleCallback, local: *const js.Local, args: anytype, comptime context: []const u8) void {
+ var try_catch: js.TryCatch = undefined;
+ try_catch.init(local);
+ defer try_catch.deinit();
+
+ local.toLocal(self.cb).callRethrow(void, args) catch |err| {
+ if (err == error.JsException or err == error.TryCatchRethrow) {
+ if (try_catch.exceptionValue()) |exc| {
+ // reportError also counts the error on the page.
+ self.exec.js.global.reportError(exc) catch |report_err| {
+ log.debug(.js, context ++ " report error", .{ .name = self.name, .err = report_err });
+ };
+ return;
+ }
+ }
+ self.exec.page.recordJsError(err);
+ log.debug(.js, context, .{ .name = self.name, .err = err });
+ };
+ }
+
fn run(ptr: *anyopaque) !?u32 {
const self: *ScheduleCallback = @ptrCast(@alignCast(ptr));
if (self.removed) {
@@ -238,27 +262,16 @@ const ScheduleCallback = struct {
switch (self.mode) {
.idle => {
const IdleDeadline = @import("IdleDeadline.zig");
- ls.toLocal(self.cb).call(void, .{IdleDeadline{}}) catch |err| {
- self.exec.page.recordJsError(err);
- log.debug(.js, "idleCallback", .{ .name = self.name, .err = err });
- };
+ self.invoke(&ls.local, .{IdleDeadline{}}, "idleCallback");
},
.animation_frame => {
const now = switch (self.exec.js.global) {
.frame => |frame| frame.window._performance.now(),
.worker => |worker| worker._performance.now(),
};
- ls.toLocal(self.cb).call(void, .{now}) catch |err| {
- self.exec.page.recordJsError(err);
- log.debug(.js, "RAF", .{ .name = self.name, .err = err });
- };
- },
- .normal => {
- ls.toLocal(self.cb).call(void, self.params) catch |err| {
- self.exec.page.recordJsError(err);
- log.debug(.js, "timer", .{ .name = self.name, .err = err });
- };
+ self.invoke(&ls.local, .{now}, "RAF");
},
+ .normal => self.invoke(&ls.local, self.params, "timer"),
}
ls.local.runMicrotasks();