How to check with javascript if connection is local host?

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 that both my server side(C#) validation is working correctly. So I like to see both the client side and server sides errors to show up.

So while I am testing I have a flag in my jquery validate stuff that just always lets invalid data go through. This way I see the client side and server errors at one go.

However right now I have to manually go and change back and forth when going from development to production.

Answers


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

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

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.


Shortest form using same mechanic as other scripts:

if ( ["localhost", "127.0.0.1", ""].includes(window.location.hostname) ) {
     console.log("It's local host !");
}

The above answers mostly solve the problem but...

  • What if localhost isn't necessarily 'localhost/'?
  • What if you want to do FE validation during development?
  • What if you want different behaviors during dev (fe validation, be validation, no validation)

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;
}

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.


Need Your Help

Learning Pascal FC

pascal pascal-fc

I'm looking for tutorials and examples on Pascal FC's channels and rendesvouz mechanisms.

Dynamically including multiple files within php for image descriptions

php

Working on implementing image descriptions to a php run gallery and can't seem to figure out how to call each text file for each individual image. I would need to place a div in the code for the im...