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 = '手机要访问页面的链接'; break; } } </script>
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/"; }
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!