Skip to content

Commit 808a77b

Browse files
committed
url: implement parse method for safer URL parsing
Implement the static parse method as per the WHATWG URL specification. Unlike the URL constructor, URL.parse does not throw on invalid input, instead returning null. This behavior allows safer parsing of URLs without the need for try-catch blocks around constructor calls. The implementation follows the steps outlined in the WHATWG URL standard, ensuring compatibility and consistency with web platform URL parsing APIs. Fixes: nodejs#52208 Refs: whatwg/url#825
1 parent 021cf91 commit 808a77b

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

lib/internal/url.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -804,6 +804,16 @@ class URL {
804804
this.#updateContext(bindingUrl.parse(input, base));
805805
}
806806

807+
static parse(input, base = undefined) {
808+
try {
809+
const url = new URL(input, base);
810+
return url;
811+
/* eslint-disable-next-line no-unused-vars */
812+
} catch (_) {
813+
return null;
814+
}
815+
}
816+
807817
[inspect.custom](depth, opts) {
808818
if (typeof depth === 'number' && depth < 0)
809819
return this;

test/fixtures/wpt/interfaces/url.idl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
interface URL {
99
constructor(USVString url, optional USVString base);
1010

11+
static URL? parse(USVString url, optional USVString base);
1112
static boolean canParse(USVString url, optional USVString base);
1213

1314
stringifier attribute USVString href;

0 commit comments

Comments
 (0)