- From: Seth Holladay <notifications@github.com>
- Date: Wed, 03 Jul 2024 17:39:22 -0700
- To: whatwg/url <url@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <whatwg/url/issues/531/2207680937@github.com>
It continues to be annoying that this doesn't work...
```js
new URL('./foo/bar.json'); // TypeError: "./foo/bar.json" cannot be parsed as a URL
```
However, for those who need a solution today, here's my suggestion: use the `Request` class. It does support relative URLs and it even respects `document.baseURI` so it works correctly in the presence of a `<base>` tag!
```js
// Current URL: https://example.com
(new Request('./foo/bar.json')).url; // => https://example.com/foo/bar.json
(new Request('https://hello.com/world')).url; // => https://hello.com/world
```
We can combine `Request` and `URL` to get a functioning URL resolver that supports relative URLs:
```js
const resolveUrl = (from, to) => {
return new URL(to || '', new Request(from).url);
};
```
```js
// Current URL: https://example.com
resolveUrl('./foo/bar.json'); // => https://example.com/foo/bar.json
resolveUrl('/api/', './foo/bar.json'); // => https://example.com/api/foo/bar.json
resolveUrl('https://hello.com/world/', 'baz'); // => https://hello.com/world/baz
resolveUrl('https://hello.com/world/', '/baz'); // => https://hello.com/baz
```
Depending on the `Request` class for this obviously isn't ideal, but also it still won't work in environments like Node where there's no base URL to resolve against. An ideal API would just return a partial URL if a base is not known.
--
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/url/issues/531#issuecomment-2207680937
You are receiving this because you are subscribed to this thread.
Message ID: <whatwg/url/issues/531/2207680937@github.com>
Received on Thursday, 4 July 2024 00:39:26 UTC