by technion · 2y ago · 0 comments
For example, on google.com, you can find:
<img class="lnXdpd" alt="Google" height="92" src="/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
But open the console and run this, and it will throw:
let x = new URL("/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
You're supposed to address this by adding the base URL on the end, but then correctly obtaining that can be brittle. If you're browsing a folder, the whole document.location is the baseURL, but if you are browsing a file (ie ends in .php or .html) it isn't. If you're taking user URLs, your browser's URL bar will add https:// automatically so people don't think about it, but they'll leave it out of an absolute URL and now you need to detect and add it if needed.
> If you're browsing a folder, the whole document.location is the baseURL, but if you are browsing a file (ie ends in .php or .html) it isn't
I’m not sure I understand what you’re saying here. The second argument in the URL constructor works as a “relative to” argument. If your URL starts with / it doesn’t matter if there’s a file or not, it’ll start from the domain root.
www.example.com + /images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com/static/ + /images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com/static/index.html + /images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com + images/foo.jpg -> www.example.com/images/foo.jpg
www.example.com/static/ + images/foo.jpg -> www.example.com/static/images/foo.jpg
www.example.com/static/index.html + images/foo.jpg -> www.example.com/static/index.htmlimages/foo.jpg (naive and wrong)
-> www.example.com/static/images/foo.jpg (extra work)
They were referring to the difference between the 5th and 6th (probably didn't notice it was an absolute path), you're referring to the first 3 together vs the others. www.example.com/static/index.html + ./images/foo.jpgI think you just misunderstand what a URL is.
The bigger point is yeah, type T isn't a parser for type U.
I guess unfortunately, I'm not sure if there is a URI-ref parser in JS that I know of … but does one ever want to do that, without first normalizing it over a base URI?
Isn't that what document.baseURI is for? At least that's my understanding:
new URL("/whatever", document.baseURI)