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
Shortest form using same mechanic as other scripts:
if ( ["localhost", "127.0.0.1", ""].includes(window.location.hostname) ) {
console.log("It's local host !");
}
const LOCAL_DOMAINS = [ "localhost", "127.0.0.1" ];
/* offline || development */
if ( LOCAL_DOMAINS.includes(location.hostname) )
{
BASE_URL_PUBLIC = location.hostname + "/folder/website/"; // your project folder
}
/* online || production */
else
{
BASE_URL_PUBLIC = location.hostname;
}
The above answers mostly solve the problem but...
One solution is to set the location hash and check it.
http://myname.foo.com/form.html#devValidation
You could add unlimited options with a switch
switch(location.hash) {}
case '#devValidation':
// log the results and post the form
break;
case '#beValidation':
// skip front end validation entirely
break;
case '#noValidation':
// skip all validation $('[name=validationType']).val('novalidation');
break;
case '#feValidation':
default:
// do fe validation
break;
}
An easy way to do this would be to just check the hostname against localhost or check your custom domain name against a substring, in this case ".local" urls, such as http://testsite.local
var myUrlPattern = '.local';
if (window.location.hostname === "localhost" || location.hostname === "127.0.0.1" || window.location.hostname.indexOf(myUrlPattern) >= 0) {
alert("It's a local server!");
}
Based on the above comments th following regular expression has helped me to verify if the url is 'localhost', any IP adress IPv4 or IPv6.
window.location.hostname.match(/localhost|[0-9]{2,3}\.[0-9]{2,3}\.[0-9]{2,3}\.[0-9]{2,3}|::1|\.local|^$/gi)
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}$/
)
);