How to check with javascript if connection is local host?

前端 未结 12 1805
孤独总比滥情好
孤独总比滥情好 2020-12-23 08:45

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

相关标签:
12条回答
  • 2020-12-23 09:14

    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!");
    
    0 讨论(0)
  • 2020-12-23 09:17

    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!");
    
    0 讨论(0)
  • 2020-12-23 09:17

    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'))
      )
    }
    
    0 讨论(0)
  • 2020-12-23 09:23

    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.

    0 讨论(0)
  • 2020-12-23 09:25

    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!");
    
    0 讨论(0)
  • 2020-12-23 09:27

    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.

    0 讨论(0)
提交回复
热议问题