判断用户客户端浏览器设备的类型

方法一,在客户端浏览器中使用js代码判断

借助navigator对象:

  • navigator.userAgent浏览器信息
  • navigator.appName浏览器版本名称
  • navigator.appVersion浏览器版本号
  • navigator.language浏览器语言
  • navigator.platform浏览器平台

示例代码如下:

<script type="text/javascript">
console.log('浏览器信息:');
console.log(navigator.userAgent);
console.log('浏览器版本名称:');
console.log(navigator.appName);
console.log('浏览器版本号:');
console.log(navigator.appVersion);
console.log('浏览器语言:');
console.log(navigator.language);
console.log('浏览器平台:');
console.log(navigator.platform);

// 从navigator.userAgent即可判断用户客户端浏览器设备的类型
// test()方法用于检测一个字符串中是否匹配某个正则模式,以下代码的功能是当用户客户端设备的类型匹配Android或webOS或iPhone或iPod或BlackBerry时,就跳转到移动端m站,否则跳转到PC端网站
window.location.href=/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)?"phone.html":"pc.html";
</script>

方法二,在服务器端使用nginx判断

根据用户设备不同返回不同样式的站点,以前经常使用的是纯前端的自适应布局,但无论是复杂性和易用性上面还是不如分开编写的好,比如我们常见的淘宝、京东……这些大型网站就都没有采用自适应,而是用分开制作的方式,根据用户请求的 user-agent 来判断是返回 PC站点还是移动端站点。

首先在 /usr/share/nginx/html 文件夹下 mkdir 分别新建两个文件夹 PC 和 mobile,vim 编辑两个 index.html 随便写点内容。

cd /usr/share/nginx/html
mkdir pc mobile
cd pc
vim index.html   # 随便写点比如 hello pc!
cd ../mobile
vim index.html   # 随便写点比如 hello mobile!

然后和设置二级域名虚拟主机时候一样,去 /etc/nginx/conf.d 文件夹下新建一个配置文件 fe.sherlocked93.club.conf:

# /etc/nginx/conf.d/fe.sherlocked93.club.conf

server {
  listen 80;
server_name fe.sherlocked93.club;

location / {
root  /usr/share/nginx/html/pc;
    if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
      root /usr/share/nginx/html/mobile;
    }
index index.html;
}
}

使用 $http_user_agent 全局变量来判断用户请求数据中的的user-agent,指向不同的root路径,返回对应站点。

参考

《你不知道的Nginx(万字详解)》

方法三,在服务器端使用编程来判断

例如,如果你使用PHP作为服务器端开发语言,那么可以Jenssegers/Agent包来判断客户端设备的类型。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注