Use JS determine whether the user opens the page using a mobile phone terminal or PC terminal

Quote: https://www.cnblogs.com/gaohuijiao/articles/6736155.html

In mobile devices more widely today, many sites have started to show mobile terminal interface, large screen size difference between the two, so the content of the show are also different. So encountered a problem, how to tell if your page is still open on the PC side in the mobile terminal, a very simple question, then we will simply point, to our company's official website, the PC-side and mobile side's official website interface are as follows:

 

 

   Object Navigator

  First, let's look at an object Navigator, Navigator object contains information about the browser, the following userAgent property is a read-only string that declares the value of the browser User-Agent header for HTTP request. So we can be judged by judging whether navigator.useragent there are certain values, such as my computer is a mac, so the printed value

 

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

 

 Do not explain the specific meaning, self-interested students Baidu, you can see that it contains the words Mac, the other is similar.

 

  How to determine that the page in the mobile terminal or PC terminal to open it?

  There are many ways online, written or difficult or simple, in fact, a line of code is enough

 

window.location.href = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ? "https://www.baidu.com/" :  "http://news.baidu.com/";

  

This code takes advantage of regular expressions and ternary operator , meaning that if a mobile terminal is open, then it jumps to "https: www.baidu.com/", if not to jump to "http: // new. baidu.com/ ", do not understand this, then I wrote the following very easy to understand it

 

if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    window.location.href = "https://www.baidu.com/";
} else {
    window.location.href = "http://news.baidu.com/";
}

 

  what? if the inside of the judgment or read? In fact, the use of regular navigator.useragent to judge whether it contains Android / webOs / iphone like strings, and the use of the modifier "i" do not case sensitive, then the method of regular judges whether to test, if such a manner It can not be understood by using a string  indexOf  method to judge.

Guess you like

Origin www.cnblogs.com/wangjing-web/p/11840496.html