Location.host vs location.hostname and cross-browser compatibility?
Use location.hostname
to extract the domain sans the port, and location.host
to include the port. Cross-browser compatibility is ensured for both.
When to wield location.host
and location.hostname
The choice between location.host
and location.hostname
is dictated by the requirement at hand. For domain validation needs or security checks based on domain, location.hostname
is your knight in shining armor. When it comes to situations requiring port number (networking apps, dev environments), location.host
pulls its weight.
Take extra caution when you're performing security-sensitive domain checking. Regular expressions like /(^|\.)domain\.com$/
are our best buddies to prevent your app from getting confused with similar domain names (nobody wants to go to fakeamazon.com instead of amazon.com, eh?).
For full URL retrieval, window.location.origin
comes to your rescue in modern browsers. However, regarding older Internet Explorer versions, you might need to press the hardwork button and format manually using protocols, hostname, and ports.
Comparing legacy and modern browsers
To ensure your application is the Absolutely Everybody of the Internet, you need to take into account compatibility with various browsers. Luckily, both location.host
and location.hostname
are like Old Friends; been there since Internet Explorer 6 and play nice with modern browsers too.
Don't just assume URLs will always behave as expected. Proxies and other network shenanigans can modify the metrics of URL properties. Suit up and employ additional checks if some Johnny Proxy tries to interfere.
Minding the pitfalls
Beware of phishing attempts and similarly named domains. Prevent these hijinks with tight validation.
For once, window.location.origin
isn't the superhero it is in modern browsers; IE10 and previous versions give it the cold shoulder. In these cases, you might need to summon all your manual concatenation powers with window.location.protocol
, window.location.hostname
, and window.location.port
.
Remember, security isn't a game (well, unless you're a hacker). Don't compromise on the wall of server-side validation while utilizing these URL-centric checks. They're your loyal sidekicks, not the main heroes of your security story.
Was this article helpful?