lifaon74/url-polyfill

Construction using window.location.href as base throws Invalid URL

Closed this issue · 5 comments

When attempting to construct a URL using a relative path and a base argument matching the current document's window.location.href, an error TypeError: Invalid URL is thrown.

Environment: IE10
Steps to reproduce:

new URL("/my/path", window.location.href)

(in my test my path was http://timelord.local:4200/candidates;location=martin_pl;date=2019-12-24)

Hum the correct thing is: new URL("/my/path", window.location.origin) or just new URL("/my/path", window.origin)

The base SHOULD not include any path

This works as expected in browser implementations, it appears only to be the polyfill which exhibits this bug.

Also I do not understand your comment. In this example, you would get a different result if you excluded the path from the base:

new URL("relative/path", "http://my.server/subfolder/index.html")

This should resolve to:

http://my.server/subfolder/relative/path

(which is exactly what it does in Chrome). Based on your comment, you are arguing that one should use the origin only (no path component) and it therefore should resolve to http://my.server/relative/path, which I don't agree with.

I know, the polyfill doesn't aim to be perfect BUT to be compact. Originally, the base parameter should only contains the origin. Nothing more. The spec evolved and now the base's path minus last part must be prepend. Because of this evolution, IE cannot support all cases ! If you really need the full implementation: https://github.com/lifaon74/whatwg-url

But you could simply use something like:

const base = new URL(window.location.href);
const path = base.pathname.split('/').slice(0, -1);
const url = new URL(path.join('/') + '/relative/path', base.origin);

Somehow, this could be patched in this polyfill. For this you could do a pull request.

Thanks for the quick responses, explanation, code snippet and relevant external link. Appreciate your help. I've done a dirty work around for my current project, but I will try to submit a pull request next time I revisit this code snippet.

Your welcome. I'll close this issue. If you have any question you can re-open it.