Home > Web Front-end > JS Tutorial > How does js determine whether the browser is PC or mobile? (two methods)

How does js determine whether the browser is PC or mobile? (two methods)

不言
Release: 2018-08-23 15:43:10
Original
6463 people have browsed it

The content of this article is about how js determines whether the browser is PC or mobile? (Two methods are introduced), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Navigator object: The Navigator object contains information about the browser. The userAgent attribute below is a read-only string that declares the value of the User Agent header used by the browser for HTTP requests. So we can judge by judging whether there are certain values ​​​​in navigator.useragent

Method 1: js code

<script type="text/javascript">
var mobileAgent = new Array("iphone", "ipod", "ipad", "android", "mobile", "blackberry", "webos", "incognito", "webmate", "bada", "nokia", "lg", "ucweb", "skyfire");
var browser = navigator.userAgent.toLowerCase();
var isMobile = false;
for (var i = 0; i < mobileAgent.length; i++) {
if (browser.indexOf(mobileAgent[i]) != -1)
 {
isMobile = true;//alert(mobileAgent[i]);
location.href = &#39;手机要访问页面的链接&#39;;
break;
}
}
</script>
Copy after login

Method 2: Regular expression

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/";
    }
Copy after login

Use regular expressions to Determine whether navigator.useragent contains strings such as Android/webOs/iphone, and use the modifier "i" to make it case-insensitive, and then use the regular method test to determine whether it satisfies

Related recommendations:

Two methods for calling self-executing functions in js

Analysis summary of local objects & built-in objects & host objects in js

The above is the detailed content of How does js determine whether the browser is PC or mobile? (two methods). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template