I want to have a check in my javascript if the page loading up is on my local machine.
The reason why I want to do that is that when I developing I like to make sure
if launching static html in browser, eg from location like file:///C:/Documents and Settings/Administrator/Desktop/
detecting "localhost" will not work. location.hostname
will return empty string. so
if (location.hostname === "localhost" || location.hostname === "127.0.0.1" || location.hostname === "")
alert("It's a local server!");
Still not a catch all but it might be a little improvement. You can now create an array of domains and use .includes
const LOCAL_DOMAINS = ["localhost", "127.0.0.1", ...];
if (LOCAL_DOMAINS.includes(window.location.hostname))
alert("It's a local server!");
This one also covers some common cases where local network IPs start with 10.0.
or 192.168.
or Bonjour like domain ending on .local
:
export function isLocalNetwork(hostname = window.location.hostname) {
return (
(['localhost', '127.0.0.1', '', '::1'].includes(hostname))
|| (hostname.startsWith('192.168.'))
|| (hostname.startsWith('10.0.'))
|| (hostname.endsWith('.local'))
)
}
Regular expression is slower*, but short and neat. Also, nobody here checks for IPv6 localhost (::1)
/localhost|127\.0\.0\.1|::1|\.local|^$/i.test(location.hostname)
It checks for general localhost, .local domain and file: (empty hostname).
*) In Chrome, performance of [].includes(...)
is the best (42 ms), followed by simple loop (for, while) with array item checking (119 ms), then [].indexOf(...) > -1
(289 ms) and finally the regexp (566 ms).
But those measurements are somehow relative, because different browsers are optimized differently. In FF 52 ESR includes
and indexOf
have similar results, regexp is 2× slower and loop 6× slower.
The location.hostname
variable gives you the current host. That should be enough for you to determine which environment you are in.
if (location.hostname === "localhost" || location.hostname === "127.0.0.1")
alert("It's a local server!");
You could detect in one of your code behind pages with c#, like this:
if ((Request.Url.Host.ToLower() == "localhost"))
{
// ..., maybe set an asp:Literal value that's in the js
}
Or if you want to do it from client script, you could check the value of window.location.host.
if (window.location.host == "localhost")
{
// Do whatever
}
Hope this helps.