Skip to content

Lightpanda: the headless browser designed for AI and automation

cdp: emit Runtime.exceptionThrown for uncaught page exceptions

Navid EMADe70c034f3a13
diff --git a/src/Notification.zig b/src/Notification.zig
index f13e8deb2..1cb187061 100644
--- a/src/Notification.zig
+++ b/src/Notification.zig
@@ -94,6 +94,7 @@ const EventListeners = struct {
javascript_dialog_opening: List = .{},
console_message: List = .{},
runtime_console_message: List = .{},
+ exception_thrown: List = .{},
model_context_tool_added: List = .{},
model_context_tool_removed: List = .{},
cookie_changed: List = .{},
@@ -125,6 +126,7 @@ const Events = union(enum) {
javascript_dialog_opening: *const JavascriptDialogOpening,
console_message: *const ConsoleMessage,
runtime_console_message: *const ConsoleMessage,
+ exception_thrown: *const ExceptionThrown,
model_context_tool_added: *const ModelContextToolEvent,
model_context_tool_removed: *const ModelContextToolEvent,
cookie_changed: *const CookieChanged,
@@ -370,6 +372,14 @@ pub const ConsoleMessage = struct {
columns: ?u32 = null,
};
+// An uncaught exception reported to a window and not cancelled by an "error"
+// listener: what Chrome logs as "Uncaught …" and sends as
+// Runtime.exceptionThrown.
+pub const ExceptionThrown = struct {
+ timestamp: u64,
+ value: js.Value,
+};
+
pub fn init(allocator: Allocator) !*Notification {
const notification = try allocator.create(Notification);
errdefer allocator.destroy(notification);
diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zig
index e369f92db..622bc8bb0 100644
--- a/src/browser/webapi/Window.zig
+++ b/src/browser/webapi/Window.zig
@@ -608,6 +608,7 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {
.message = err.toStringSlice() catch "Unknown error",
});
}
+ notifyExceptionThrown(err, frame);
return;
}
@@ -667,6 +668,18 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {
});
}
}
+ if (!event._prevent_default) {
+ notifyExceptionThrown(err, frame);
+ }
+}
+
+// An error event left uncancelled leaves the exception "uncaught": CDP
+// clients learn about it through Runtime.exceptionThrown.
+fn notifyExceptionThrown(err: js.Value, frame: *Frame) void {
+ frame._session.notification.dispatch(.exception_thrown, &.{
+ .timestamp = lp.datetime.timestamp(.boot),
+ .value = err,
+ });
}
pub fn matchMedia(_: *const Window, query: []const u8, frame: *Frame) !*MediaQueryList {
diff --git a/src/server/cdp/CDP.zig b/src/server/cdp/CDP.zig
index 9adb8beb3..9e16a362e 100644
--- a/src/server/cdp/CDP.zig
+++ b/src/server/cdp/CDP.zig
@@ -940,10 +940,12 @@ pub const BrowserContext = struct {
pub fn runtimeEnable(self: *BrowserContext) !void {
try self.notification.register(.runtime_console_message, self, onRuntimeConsoleMessage);
+ try self.notification.register(.exception_thrown, self, onExceptionThrown);
}
pub fn runtimeDisable(self: *BrowserContext) void {
self.notification.unregister(.runtime_console_message, self);
+ self.notification.unregister(.exception_thrown, self);
}
// Registers for the download notifications dispatched by Frame when a
@@ -1183,6 +1185,13 @@ pub const BrowserContext = struct {
return @import("domains/runtime.zig").consoleMessage(arena, self, msg);
}
+ fn onExceptionThrown(ctx: *anyopaque, msg: *const Notification.ExceptionThrown) !void {
+ const self: *BrowserContext = @ptrCast(@alignCast(ctx));
+ const arena = self.acquireNotificationArena();
+ defer self.releaseNotificationArena();
+ return @import("domains/runtime.zig").exceptionThrown(arena, self, msg);
+ }
+
fn acquireNotificationArena(self: *BrowserContext) Allocator {
self.cdp.notification_depth += 1;
return self.notification_arena;
diff --git a/src/server/cdp/domains/runtime.zig b/src/server/cdp/domains/runtime.zig
index 2a3b44042..101f23790 100644
--- a/src/server/cdp/domains/runtime.zig
+++ b/src/server/cdp/domains/runtime.zig
@@ -20,6 +20,7 @@ const std = @import("std");
const CDP = @import("../CDP.zig");
const js = @import("../../../browser/js/js.zig");
+const v8 = js.v8;
const Notification = @import("../../../Notification.zig");
const repeat = @import("../../../string.zig").repeat;
@@ -168,6 +169,76 @@ pub fn consoleMessage(arena: Allocator, bc: *CDP.BrowserContext, event: *const N
}, .{ .session_id = session_id });
}
+const ExceptionDetails = struct {
+ exceptionId: u32,
+ text: []const u8,
+ lineNumber: u32,
+ columnNumber: u32,
+ url: ?[]const u8,
+ exception: RemoteObject,
+ executionContextId: i32,
+};
+
+var next_exception_id: std.atomic.Value(u32) = .init(1);
+
+pub fn exceptionThrown(arena: Allocator, bc: *CDP.BrowserContext, event: *const Notification.ExceptionThrown) !void {
+ // Like consoleAPICalled: the primary session's inspector mints the handle.
+ const session_id = bc.session_id orelse return;
+ const inspector_session = try bc.inspectorSession(session_id);
+ const frame = bc.mainFrame() orelse return error.FrameNotLoaded;
+
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+
+ const value = event.value;
+ const remote_object = try inspector_session.getRemoteObject(&ls.local, "", value);
+ defer remote_object.deinit();
+
+ var exception = RemoteObject{
+ .type = try remote_object.getType(arena),
+ .subtype = try remote_object.getSubtype(arena),
+ .className = try remote_object.getClassName(arena),
+ .description = try remote_object.getDescription(arena),
+ .objectId = try remote_object.getObjectId(arena),
+ };
+ try exception.setPrimitive(arena, value);
+
+ // Where the exception was thrown. V8's line is 1-based, CDP's 0-based.
+ var line: u32 = 0;
+ var column: u32 = 0;
+ var url: ?[]const u8 = null;
+ if (v8.v8__Exception__CreateMessage(ls.local.isolate.handle, value.handle)) |message| {
+ const l = v8.v8__Message__GetLineNumber(message, ls.local.handle);
+ if (l > 0) {
+ line = @intCast(l - 1);
+ }
+ const c = v8.v8__Message__GetStartColumn(message);
+ if (c > 0) {
+ column = @intCast(c);
+ }
+ if (v8.v8__Message__GetScriptResourceName(message)) |name| {
+ const name_value = js.Value{ .local = &ls.local, .handle = name };
+ if (name_value.isString()) |str| {
+ url = try str.toSliceWithAlloc(arena);
+ }
+ }
+ }
+
+ return bc.cdp.sendEvent("Runtime.exceptionThrown", .{
+ .timestamp = event.timestamp,
+ .exceptionDetails = ExceptionDetails{
+ .exceptionId = next_exception_id.fetchAdd(1, .monotonic),
+ .text = "Uncaught",
+ .lineNumber = line,
+ .columnNumber = column,
+ .url = url,
+ .exception = exception,
+ .executionContextId = bc.inspector().getContextId(&ls.local),
+ },
+ }, .{ .session_id = session_id });
+}
+
const testing = @import("../testing.zig");
test "cdp.runtime: inspector-handled methods pass through" {
@@ -255,6 +326,63 @@ test "cdp.runtime: inspector events go to the session that enabled them" {
try testing.expectEqual(1, try countSentEvents(&ctx, "Runtime.executionContextCreated", "SID-PRIMARY"));
}
+test "cdp.runtime: an uncaught exception emits Runtime.exceptionThrown" {
+ testing.silenceLog(&.{.js});
+
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ var bc = try ctx.loadBrowserContext(.{ .id = "BID-EXC", .url = "hi.html", .target_id = "FID-0000000EXC".* });
+ try ctx.processMessage(.{ .id = 60, .method = "Runtime.enable" });
+
+ const frame = bc.mainFrame() orelse unreachable;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ // An inline handler's exception is reported to the window and nothing
+ // cancels it: uncaught.
+ _ = try ls.local.exec(
+ \\document.body.setAttribute('onclick', "throw new TypeError('boom')");
+ \\document.body.click();
+ , null);
+
+ try ctx.expectSentEvent("Runtime.exceptionThrown", .{
+ .exceptionDetails = .{
+ .text = "Uncaught",
+ .exception = .{ .type = "object", .subtype = "error", .className = "TypeError" },
+ },
+ }, .{});
+}
+
+test "cdp.runtime: an exception whose error event is cancelled is not reported" {
+ testing.silenceLog(&.{.js});
+
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ var bc = try ctx.loadBrowserContext(.{ .id = "BID-EXC2", .url = "hi.html", .target_id = "FID-000000EXC2".* });
+ try ctx.processMessage(.{ .id = 61, .method = "Runtime.enable" });
+
+ const frame = bc.mainFrame() orelse unreachable;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ // preventDefault() on the error event marks the exception handled, as
+ // in Chrome; only the second report is uncaught.
+ _ = try ls.local.exec(
+ \\const quiet = (e) => e.preventDefault();
+ \\window.addEventListener('error', quiet);
+ \\reportError('quiet');
+ \\window.removeEventListener('error', quiet);
+ \\reportError('loud');
+ , null);
+
+ try ctx.expectSentEvent("Runtime.exceptionThrown", .{
+ .exceptionDetails = .{ .exception = .{ .type = "string", .value = "loud" } },
+ }, .{});
+ try testing.expectEqual(1, try countSentEvents(&ctx, "Runtime.exceptionThrown", "SID-X"));
+}
+
test "cdp.runtime: consoleAPICalled type matches the console method" {
testing.silenceLog(&.{.js});