Javascript 如果连接是本地主机,如何使用javascript检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3162457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:29:51  来源:igfitidea点击:

How to check with javascript if connection is local host?

javascriptjquerylocalhost

提问by chobo2

I want to have a check in my javascript if the page loading up is on my local machine.

如果加载的页面在我的本地机器上,我想检查我的 javascript。

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.

我想要这样做的原因是,当我开发时,我喜欢确保我的服务器端(C#)验证都正常工作。所以我喜欢看到客户端和服务器端的错误都出现。

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.

因此,当我进行测试时,我的 jquery 验证内容中有一个标志,它总是让无效数据通过。通过这种方式,我可以一次性看到客户端和服务器错误。

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

但是现在我必须在从开发到生产时手动来回更改。

回答by Unicron

The location.hostnamevariable gives you the current host. That should be enough for you to determine which environment you are in.

location.hostname变量为您提供当前主机。这应该足以让您确定您所处的环境。

if (location.hostname === "localhost" || location.hostname === "127.0.0.1")
    alert("It's a local server!");

回答by Tomasz Bujnowski

if launching static html in browser, eg from location like file:///C:/Documents and Settings/Administrator/Desktop/detecting "localhost" will not work. location.hostnamewill return empty string. so

如果在浏览器中启动静态 html,例如从file:///C:/Documents and Settings/Administrator/Desktop/检测“本地主机”之类的位置将不起作用。location.hostname将返回空字符串。所以

if (location.hostname === "localhost" || location.hostname === "127.0.0.1" || location.hostname === "")
    alert("It's a local server!");

回答by daniele bertella

Still not a catch all but it might be a little improvement. You can now create an array of domains and use .includes

仍然不是全部,但可能会有所改进。您现在可以创建域数组并使用.includes

const LOCAL_DOMAINS = ["localhost", "127.0.0.1", ...];

if (LOCAL_DOMAINS.includes(window.location.hostname))
  alert("It's a local server!");

回答by TarmoPikaro

Shortest form using same mechanic as other scripts:

使用与其他脚本相同的机制的最短形式:

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

回答by Summit

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

一个简单的方法是根据本地主机检查主机名或根据子字符串检查您的自定义域名,在这种情况下是“.local”网址,例如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!");
}

回答by Alireza

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

这就是在React 中检查它的方式,注册 service worker,通过检查主机名(包括localhostIPv6)以及匹配以127开头来检查您是否在 localhost 上的好方法 :

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

回答by Samuel Meacham

You could detect in one of your code behind pages with c#, like this:

您可以使用 c# 在您的代码隐藏页面之一中检测,如下所示:

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.

或者,如果您想从客户端脚本执行此操作,您可以检查 window.location.host 的值。

if (window.location.host == "localhost")
{
    // Do whatever
}

Hope this helps.

希望这可以帮助。

回答by Shanimal

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)
  • 如果 localhost 不一定是“localhost/”怎么办?
  • 如果您想在开发过程中进行 FE 验证怎么办?
  • 如果您在开发期间想要不同的行为怎么办
    fe 验证、be 验证、no 验证

One solution is to set the location hash and check it.

一种解决方案是设置位置哈希并检查它。

http://myname.foo.com/form.html#devValidation

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

回答by mikiqex

Regular expression is slower*, but short and neat. Also, nobody here checks for IPv6 localhost (::1)

正则表达式速度较慢*,但简洁明了。此外,这里没有人检查 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).

它检查常规本地主机、.local 域和文件:(空主机名)。

*) 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 includesand indexOfhave similar results, regexp is 2× slower and loop 6× slower.

*) 在 Chrome 中,性能[].includes(...)最好(42 毫秒),其次是带有数组项检查的简单循环(for、while)(119 毫秒),然后是[].indexOf(...) > -1(289 毫秒),最后是正则表达式(566 毫秒)。但是这些测量值在某种程度上是相对的,因为不同的浏览器的优化方式不同。在 FF 52 ESR 中includesindexOf具有相似的结果,regexp 慢 2 倍,循环慢 6 倍。

回答by saddy

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.

基于上述评论,以下正则表达式帮助我验证了 url 是否为“本地主机”、任何 IP 地址 IPv4 或 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)