Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check with javascript if connection is local host?

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!");

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!");

That's how it get checked in React, register service worker, good way to check if you are on localhost by checking hostname, including localhost and IPv6, and matching start with 127:

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);