Skip to content

Commit 37340dc

Browse files
committed
dom: implement document.cookie
1 parent f034065 commit 37340dc

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/html/document.zig

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ const Location = @import("location.zig").Location;
3333
const collection = @import("../dom/html_collection.zig");
3434
const Walker = @import("../dom/walker.zig").WalkerDepthFirst;
3535

36+
const UserContext = @import("../user_context.zig").UserContext;
37+
const Cookie = @import("../storage/cookie.zig").Cookie;
38+
3639
// WEB IDL https://html.spec.whatwg.org/#the-document-object
3740
pub const HTMLDocument = struct {
3841
pub const Self = parser.DocumentHTML;
@@ -81,14 +84,18 @@ pub const HTMLDocument = struct {
8184
}
8285
}
8386

84-
// TODO: not implemented by libdom
85-
pub fn get_cookie(_: *parser.DocumentHTML) ![]const u8 {
86-
return error.NotImplemented;
87+
pub fn get_cookie(_: *parser.DocumentHTML, allocator: std.mem.Allocator, userctx: UserContext) ![]const u8 {
88+
var buf: std.ArrayListUnmanaged(u8) = .{};
89+
defer buf.deinit(allocator);
90+
try userctx.cookie_jar.forRequest(&userctx.url.uri, buf.writer(allocator), .{ .navigation = true });
91+
return buf.toOwnedSlice(allocator);
8792
}
8893

89-
// TODO: not implemented by libdom
90-
pub fn set_cookie(_: *parser.DocumentHTML, _: []const u8) ![]const u8 {
91-
return error.NotImplemented;
94+
pub fn set_cookie(_: *parser.DocumentHTML, allocator: std.mem.Allocator, userctx: UserContext, cookie_str: []const u8) ![]const u8 {
95+
const c = try Cookie.parse(allocator, &userctx.url.uri, cookie_str);
96+
try userctx.cookie_jar.add(c, std.time.timestamp());
97+
98+
return cookie_str;
9299
}
93100

94101
pub fn get_title(self: *parser.DocumentHTML) ![]const u8 {
@@ -258,4 +265,12 @@ pub fn testExecFn(
258265
.{ .src = "list.length", .ex = "1" },
259266
};
260267
try checkCases(js_env, &getElementsByName);
268+
269+
var cookie = [_]Case{
270+
.{ .src = "document.cookie", .ex = "" },
271+
.{ .src = "document.cookie = 'name=Oeschger; SameSite=None; Secure'", .ex = "name=Oeschger; SameSite=None; Secure" },
272+
.{ .src = "document.cookie = 'favorite_food=tripe; SameSite=None; Secure'", .ex = "favorite_food=tripe; SameSite=None; Secure" },
273+
.{ .src = "document.cookie", .ex = "name=Oeschger; favorite_food=tripe" },
274+
};
275+
try checkCases(js_env, &cookie);
261276
}

0 commit comments

Comments
 (0)