Florestan Korp
Florestan Korp

Reputation: 711

Differences between Firefox and Chromium JavaScript URL validation with new URL()

I'm trying to validate URLs in JavaScript and according to MDN JavaScript's URL API is compatible with Chromium browsers and Firefox. However the behaviour varies between the two engines. Specifically it seems like Chromium browsers are far more lenient and automatically apply encoding where Firefox doesn't.

I've tried encoding the URL myself first before validating with encodeURI('https://abc.co m'), but Firefox also doesn't accept https://abc.c%20m as a valid URL, so I'm stumped as to how I can have a good way to support both browsers without having to resort to regex.

I'm not sure why they are different, or who is correct. What is a consistent, correct approach with cross browser support for this?

enter image description here


Runnable snippet:

const url = new URL("https://abc.c%20m");
console.log(url.hostname);

Upvotes: 1

Views: 107

Answers (1)

jsejcksn
jsejcksn

Reputation: 33856

Browsers can have bugs, just like all other software. According to your screenshots, it appears that Chrome didn't properly parse the URL according to the specification — specifically step 4 (decode) of § 3.5 Host parsing. A space character (whether percent-encoded or not) isn't allowed in a hostname.

In cases like this — where you have to work around bugs in the implementation code used by native APIs in your runtime (e.g. the URL constructor or its canParse() static method) — you can either write your own JavaScript implementation of a URL parser that conforms to the spec or audit the source code of an existing one that claims to do so 1 and use it instead.


1 One such example is the whatwg-url package (repository) — here's a link to a demo using the input in your question: https://jsdom.github.io/whatwg-url/#url=aHR0cHM6Ly9hYmMuYyUyMG0=&base=YWJvdXQ6Ymxhbms=

Upvotes: 2

Related Questions