Skip to content

Commit 16e7c08

Browse files
committed
handle empty hashes in Location
1 parent 19b9ba8 commit 16e7c08

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

src/browser/html/location.zig

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717
// along with this program. If not, see <https://www.gnu.org/licenses/>.
1818

1919
const std = @import("std");
20-
const Uri = std.Uri;
21-
2220
const Page = @import("../page.zig").Page;
2321
const URL = @import("../url/url.zig").URL;
2422

@@ -44,10 +42,19 @@ pub const Location = struct {
4442
}
4543

4644
pub fn set_hash(_: *const Location, hash: []const u8, page: *Page) !void {
47-
const normalized_hash = if (hash[0] == '#')
48-
hash
49-
else
50-
try std.fmt.allocPrint(page.arena, "#{s}", .{hash});
45+
const normalized_hash = blk: {
46+
if (hash.len == 0) {
47+
const old_url = page.url.raw;
48+
49+
break :blk if (std.mem.indexOfScalar(u8, old_url, '#')) |index|
50+
old_url[0..index]
51+
else
52+
old_url;
53+
} else if (hash[0] == '#')
54+
break :blk hash
55+
else
56+
break :blk try std.fmt.allocPrint(page.arena, "#{s}", .{hash});
57+
};
5158

5259
return page.navigateFromWebAPI(normalized_hash, .{ .reason = .script }, .replace);
5360
}

src/tests/html/location.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,19 @@
1515
</script>
1616

1717
<script id=location_hash>
18+
location.hash = "";
19+
testing.expectEqual("", location.hash);
20+
testing.expectEqual('http://localhost:9582/src/tests/html/location.html', location.href);
21+
1822
location.hash = "#abcdef";
1923
testing.expectEqual("#abcdef", location.hash);
2024
testing.expectEqual('http://localhost:9582/src/tests/html/location.html#abcdef', location.href);
2125

2226
location.hash = "xyzxyz";
2327
testing.expectEqual("#xyzxyz", location.hash);
2428
testing.expectEqual('http://localhost:9582/src/tests/html/location.html#xyzxyz', location.href);
29+
30+
location.hash = "";
31+
testing.expectEqual("", location.hash);
32+
testing.expectEqual('http://localhost:9582/src/tests/html/location.html', location.href);
2533
</script>

0 commit comments

Comments
 (0)