Skip to content

Commit 4099696

Browse files
Add Runtime.addBinding
Signed-off-by: Francis Bouvier <[email protected]>
1 parent 7abb727 commit 4099696

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/cdp/runtime.zig

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const RuntimeMethods = enum {
1313
enable,
1414
runIfWaitingForDebugger,
1515
evaluate,
16+
addBinding,
1617
};
1718

1819
pub fn runtime(
@@ -28,6 +29,7 @@ pub fn runtime(
2829
.enable => enable(alloc, id, scanner, ctx),
2930
.runIfWaitingForDebugger => runIfWaitingForDebugger(alloc, id, scanner, ctx),
3031
.evaluate => evaluate(alloc, id, scanner, ctx),
32+
.addBinding => addBinding(alloc, id, scanner, ctx),
3133
};
3234
}
3335

@@ -171,3 +173,54 @@ fn evaluate(
171173
};
172174
return result(alloc, id, Resp, Resp{}, msg.sessionID);
173175
}
176+
177+
fn addBinding(
178+
alloc: std.mem.Allocator,
179+
_id: ?u16,
180+
scanner: *std.json.Scanner,
181+
ctx: *Ctx,
182+
) ![]const u8 {
183+
184+
// input
185+
const Params = struct {
186+
name: []const u8,
187+
executionContextId: ?u8 = null,
188+
};
189+
const msg = try getMsg(alloc, Params, scanner);
190+
const id = _id orelse msg.id.?;
191+
const params = msg.params.?;
192+
if (params.executionContextId) |contextId| {
193+
std.debug.assert(contextId == ctx.state.executionContextId);
194+
}
195+
196+
const script = try std.fmt.allocPrint(alloc, "globalThis['{s}'] = {{}};", .{params.name});
197+
defer alloc.free(script);
198+
199+
const session = ctx.browser.currentSession();
200+
const res = try runtimeEvaluate(session.alloc, id, session.env, script, "addBinding");
201+
defer res.deinit(session.alloc);
202+
203+
return result(alloc, id, null, null, msg.sessionID);
204+
}
205+
206+
// caller is the owner of JSResult returned
207+
fn runtimeEvaluate(
208+
alloc: std.mem.Allocator,
209+
id: u16,
210+
env: jsruntime.Env,
211+
script: []const u8,
212+
comptime name: []const u8,
213+
) !jsruntime.JSResult {
214+
var res = jsruntime.JSResult{};
215+
try env.run(alloc, script, "cdp.Runtime." ++ name, &res, null);
216+
217+
if (!res.success) {
218+
std.log.err("'{s}' id {d}, result: {s}", .{ name, id, res.result });
219+
if (res.stack) |stack| {
220+
std.log.err("'{s}' id {d}, stack: {s}", .{ name, id, stack });
221+
}
222+
return error.CDPRuntimeEvaluate;
223+
}
224+
std.log.debug("'{s}' id {d}, result: {s}", .{ name, id, res.result });
225+
return res;
226+
}

0 commit comments

Comments
 (0)