How to check with javascript if connection is local host?

前端 未结 12 1848
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题