admin管理员组

文章数量:1129170

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.

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.

Share Improve this question edited Apr 27, 2016 at 8:30 Damjan Pavlica 33.9k10 gold badges75 silver badges78 bronze badges asked Jul 1, 2010 at 23:50 chobo2chobo2 85.7k207 gold badges548 silver badges860 bronze badges 1
  • 6 I would just caution anybody using of any of these methods in any of these answers to "add" functionality to the system, especially if said functionality could be used to expose otherwise secure information or data in your system. Using this technique to "remove" functionality makes sense, however. For example, if you want to suppress firing analytics tracking in your development environment, even though you do it in your production environment. Just think carefully about what you're exposing through a browser-side conditional or toggle and how it could become a security vulnerability. – Javid Jamae Commented Apr 2, 2018 at 4:58
Add a comment  | 

15 Answers 15

Reset to default 294

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

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}$/
    )
);

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

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 following code checks whether an address is localhost, that is, whether it points to the same device from which this request is made.

export function isLocalHost(hostname = window.location.hostname) {
  return ['localhost', '127.0.0.1', '', '::1'].includes(hostname)
}

The following code also checks if the request goes into the local network. Some common cases where local network IPs start with 10.0. or 192.168. or mDNS / Bonjour like domains 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.'))
    || (hostname.endsWith('.local'))
  )
}
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;
}

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.

Many of the answers here miss some edge-cases. For example, depending on DNS/hosts/etc, you could have something.localhost.

So here is a slightly more comprehensive ES6 answer:

const localHost = ['localhost', '127.0.0.1', '::1', ''].includes(window.location.hostname) || window.location.hostname.endsWith('.localhost')

This is the simplest and most reliable regex-based solution:

/(?:^|\.)localhost$|^(?:\[::1\]|127(?:\.\d+){3})?$/i.test(location.hostname)

It matches all host names that mean localhost with no special configuration (so not .local, etc.):

  • localhost - case-insensitive match
  • *.localhost - these resolve to localhost automatically; also case-insensitive
  • [::1] - the only IPV6 loopback address; browsers (at least Firefox) redirect equivalent forms like [0::0:0:1] to [::1], so there's no need for a more complex regex here
  • 127.#.#.# where # means a number (1 or more digits 0-9); there's no need to make a more complex regex for specific digits since no top-level domains consist of only digits (I didn't check the standards, but I doubt this is or will ever be allowed)
  • empty string - for file: protocol on the local machine

Here's a simple tester:

const input = document.querySelector('input');
const checkbox = document.querySelector('input[type=checkbox]');
function update() { checkbox.checked = /(?:^|\.)localhost$|^(?:\[::1\]|127(?:\.\d+){3})?$/i.test(input.value); }
input.oninput = update; update();
function preset() { input.value = this.innerText.trim(); update(); }
for (const button of document.querySelectorAll('button')) button.onclick = preset;
<code>location.hostname: </code><input placeholder="(empty)" /> <input type=checkbox disabled /> <code>== localhost</code>
<br/><button>&nbsp;</button> <button>localhost</button> <button>www.etc.localhost</button> <button>[::1]</button> <button>127.0.0.0</button> <button>127.0.0.1</button> <button>127.255.42.0</button>
<br/><button>example.local</button> <button>localhost.com</button> <button>notlocalhost</button> <button>[2606:4700:4700::1111]</button> <button>1.1.1.1</button> <button>10.0.0.1</button> <button>192.168.0.1</button>

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.

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)

It is now possible to infer that the page has been loaded from your local machine when window.isSecureContext is set, but the URL scheme isn't either https:// or wss://:

if (isSecureContext && !['https:', 'wss:'].includes(location.protocol)) {
    // locally-delivered context (eg: http://localhost/ or file://...)
}

This is a much more reliable technique than the existing answers for modern browsers (everything since April 2018) for the majority of "local development" use cases:

  • Detects when the hostname resolves to an IP in the 127.0.0.0/8 or ::1/128 address ranges.
  • Also detects file: and blob: URLs, not just http: URLs.
  • False negatives when using https://localhost/ or similar, but you could account for that.
  • Potential false negative when loaded via an <iframe> from an insecure context. It is possible to check location.ancestorOrigins if you really want to account for that.

本文标签: jqueryHow to check with javascript if connection is local hostStack Overflow