检测桌面浏览器的初步想法

必须指出,实际上并没有一种确切的方法可以判定终端是否一个桌面浏览器,但是,我们总是可以把多种条件的组合一起去检查,进而来综合判断出,对方终端是否一个非移动类型的终端。这里尝试列出几点:

  • ua 字符串没有返回 Android/iPhone/WinPhone 等特征的,很可能是桌面浏览器;
  • window.screenX 该值返回浏览器窗体左上角在屏幕的坐标位置。因为移动终端通常总是独占屏幕的,也是在0, 0的坐标。如果 screenX 返回非 0,很可能是桌面浏览器;
  • window.devicePixelRatio and screen.width 若然屏幕密度 devicePixelRatio 为 1,并且等于屏幕分辨率 screen.width,很可能是桌面浏览器;
  • 分辨率能不能判断是否移动终端?有些手机的屏幕非常高,据此来判断也不容易;
  • window.orientation 桌面浏览器很少是 portrait 纵向的。

外国已经有人利用以上的特性写成一个 js 库,源码如下:

/*
ReView.js 0.65b. The Responsive Viewport. responsiveviewport.com.
Developed by Edward Cant. @opticswerve.
*/
function Viewport() {
  this.viewport = function(a) {
    var b = document,
        d = b.documentElement;
    b.head = b.head || b.getElementsByTagName("head")[0];
    var e = screen,
        c = this,
        f = window;
    c.bScaled = !1;
    c.bSupported = !0;
    b.addEventListener === a ? c.bSupported = !1 : b.querySelector === a ? c.bSupported = !1 : f !== parent ? c.bSupported = !1 : f.orientation === a && (c.bSupported = !1);
    c.updateOrientation();
    c.updateScreen();
    c.dpr = 1;
    var g = f.devicePixelRatio;
    g === a ? c.bSupported = !1 : c.dpr = g;
    c.fromHead();
    this.meta !== a && (c.iHeight = c.height, c.iMaxScale = c.maxScale, c.iMinScale =
    c.minScale, c.iUserScalable = c.bUserScalable, c.iWidth = c.width);
    c.defaultWidth = 980;
    e.width > c.defaultWidth && (c.defaultWidth = e.width);
    e.height > c.defaultWidth && (c.defaultWidth = e.height);
    c.ready(function() {
      if (c.bSupported) {
        if (f.screenX !== 0) c.bSupported = false;
        else if (c.width !== a) {
          var e;
          if (d.offsetHeight <= d.clientHeight) {
            e = d.style.height;
            d.style.height = d.clientHeight + 128 + "px"
          }
          if (c.width === "device-width") {
            if (d.clientWidth !== c.screenWidth) c.bSupported = false
          } else if (c.width !== d.clientWidth) c.bSupported = false;
          e === "" ? d.style.height = "auto" : e !== a && (d.style.height = e)
        }
        if (c.bSupported) {
          b.addEventListener("touchend", function() {
            var b = (new Date).getTime();
            if (c.lastTouch !== a && b - c.lastTouch < 500 && c.bUserScalable === true) c.bScaled = true;
            c.lastTouch = b
          }, false);
          b.addEventListener("gestureend", function(a) {
            if (a.scale !== 1 && c.bUserScalable === true) c.bScaled = true
          }, false);
          b.addEventListener("resize", function() {
            c.updateCheck()
          }, false);
          b.addEventListener("orientationchange", function() {
            var b = c.orientation;
            c.updateOrientation();
            if (b !== c.orientation) {
              c.updateScreen();
              if (c.bUserScalable === true) c.bScaled = true;
              c.orientationChangePolicy !== a && c.orientationChangePolicy()
            }
          }, false)
        }
      }
      c.readyPolicy !== a && c.readyPolicy()
    })
  };
  this.fromContentString = function(a) {
    for (var a = a.split(","), b, d, e = 0; e < a.length; e++) b = a[e].split("="), 2 === b.length && (d = b[0].trim(), b = b[1].trim(), isNaN(parseFloat(b)) || (b = parseFloat(b)), "width" === d ? this.width = b : "height" === d ? this.height = b : "initial-scale" === d ? this.initialScale = b : "maximum-scale" === d ? this.maxScale = b : "minimum-scale" === d ? this.minScale = b : "user-scalable" === d && (this.bUserScalable = "no" === b ? !1 : !0))
  };
  this.fromHead = function() {
    var a = this.meta = document.head.querySelector("meta[name=viewport]");
    null === a ? this.meta = void 0 : a.hasAttribute("content") && this.fromContentString(a.getAttribute("content"))
  };
  this.ready = function(a) {
    var b = document;
    b.addEventListener && b.addEventListener("DOMContentLoaded", function() {
      b.removeEventListener("DOMContentLoaded", arguments.callee, !1);
      a()
    }, !1)
  };
  this.setDefault = function(a, b) {
    this.bUserScalable = !0;
    this.height = void 0;
    this.maxScale = 5;
    this.minScale = 0.25;
    this.width = this.defaultWidth;
    this.update(a, b)
  };
  this.setMobile = function(a, b) {
    this.bScaled ? b() : (void 0 === this.iWidth ? (this.bUserScalable = !1, this.height = void 0, this.minScale = this.maxScale = 1, this.width = "device-width") : (this.bUserScalable = this.iUserScalable, this.height = this.iHeight, this.maxScale = this.iMaxScale, this.minScale = this.iMinScale, this.width = this.iWidth), this.update(a, b))
  };
  this.toString = function() {
    var a = "";
    void 0 !== this.width && (a += "width=" + this.width + ", ");
    void 0 !== this.height && (a += "height=" + this.height + ", ");
    void 0 !== this.maxScale && (a += "maximum-scale=" + this.maxScale + ", ");
    void 0 !== this.minScale && (a += "minimum-scale=" + this.minScale + ", ");
    !0 === this.bUserScalable ? a += "user-scalable=yes" : !1 === this.bUserScalable && (a += "user-scalable=no");
    return a
  };
  this.update = function(a, b) {
    var d = this;
    if (d.bSupported) {
      d.updateFailure = b;
      d.updateSuccess = a;
      var e = d.width;
      "device-width" === e && (e = d.screenWidth);
      e = d.prevWidth;
      "device-width" === e ? e = d.screenWidth : void 0 === e && (e = document.documentElement.clientWidth);
      d.updateMeta();
      d.updateTimeout = setTimeout(function() {
        d.updateCheck()
      }, 500)
    } else b()
  };
  this.updateCheck = function() {
    if (void 0 !== this.updateTimeout) {
      var a = !1,
          b = document.documentElement.clientWidth;
      this.width === b ? a = !0 : "device-width" === this.width && this.screenWidth === b && (a = !0);
      clearTimeout(this.updateTimeout);
      this.updateTimeout = void 0;
      a ? (this.prevWidth = this.width, this.updateSuccess(), this.viewportChange()) : (this.bSupported = !1, this.updateFailure());
      this.updateSuccess =
      this.updateFailure = void 0
    }
  };
  this.updateMeta = function() {
    var a = document,
        b = this.meta;
    void 0 === b ? (b = this.meta = a.createElement("meta"), b.setAttribute("name", "viewport"), b.setAttribute("content", this.toString()), a.head.appendChild(b)) : b.setAttribute("content", this.toString())
  };
  this.updateOrientation = function() {
    var a = window.orientation;
    this.orientation = a = 0 === a || 180 === a ? "portrait" : 90 === a || -90 === a ? "landscape" : document.documentElement.clientWidth > document.documentElement.clientHeight ? "landscape" : "portrait"
  };
  this.updateScale = function() {
    this.scale = this.screenWidth / window.innerWidth
  };
  this.updateScreen = function() {
    var a = this.screenHeight = screen.height,
        b = this.screenWidth = screen.width;
    "portrait" === this.orientation ? b > a && (this.screenHeight = b, this.screenWidth = a) : b < a && (this.screenHeight = b, this.screenWidth = a)
  };
  this.viewportChange = function() {
    var a = document.createEvent("Event");
    a.initEvent("viewportChange", !0, !0);
    a.bUserScalable = this.bUserScalable;
    a.maxScale = this.maxScale;
    a.minScale = this.minScale;
    a.width = this.width;
    document.dispatchEvent(a)
  };
  return !0
}
var reView;
(function(a) {
  reView = new ReView;
  if (reView.v.bSupported) try {
    if ("sessionStorage" in a && null !== a.sessionStorage) {
      var b = sessionStorage.getItem("reViewMode");
      "core" === reView.mode && "default" === b ? reView.setDefault() : "default" === reView.mode && "core" === b && reView.setCore()
    } else reView.v.bSupported = !1
  } catch (d) {
    reView.v.bSupported = !1
  }
})(window);

function ReView() {
  this.mode = "default";
  this.v = new Viewport;
  this.v.viewport();
  this.v.readyPolicy = function() {
    reView.ready()
  };
  this.v.bSupported && "device-width" === this.v.width && (this.mode = "core");
  this.failure = function() {
    var a = reView;
    a.mode === "default" && a.v.iWidth !== void 0 && window.location.reload();
    a.failurePolicy !== void 0 && a.failurePolicy()
  };
  this.ready = function() {
    var a = document.getElementsByClassName("reView"),
        b = a.length,
        d = reView;
    if (d.v.bSupported) {
      for (d.mode === "default" && sessionStorage.getItem("reViewMode") !== "core" && d.success(); b--;) a[b].style.display = "inline";
      document.body.addEventListener("click", function(a) {
        if (a.target.hasAttribute("class") && a.target.getAttribute("class").indexOf("reView") > -1) {
          a.preventDefault();
          d.mode === "default" ? d.setCore() : d.mode === "core" && d.setDefault()
        }
      })
    } else
    for (screen.width >= 1024 && d.success(); b--;) a[b].style.display = "none"
  };
  this.setCore = function() {
    if (this.mode === "core") this.success();
    else if (this.v.bSupported) {
      try {
        sessionStorage.setItem("reViewMode", "core")
      } catch (a) {}
      this.v.setMobile(function() {
        reView.mode = "core";
        reView.success()
      }, reView.failure)
    } else this.failure()
  };
  this.setDefault = function() {
    if (this.mode === "default") this.success();
    else if (this.v.bSupported) {
      try {
        sessionStorage.setItem("reViewMode", "default")
      } catch (a) {}
      this.v.setDefault(function() {
        reView.mode = "default";
        reView.success()
      }, reView.failure)
    } else this.failure()
  };
  this.success = function() {
    var a = reView;
    a.v.bSupported && a.updateAnchors();
    a.successPolicy !== void 0 && a.successPolicy()
  };
  this.updateAnchors = function() {
    var a = document.getElementsByClassName("reView"),
        b = a.length;
    if (this.mode === "core") for (; b--;) a[b].innerHTML = a[b].hasAttribute("data-coreText") ? a[b].getAttribute("data-coreText") : "Default View";
    else
    for (; b--;) a[b].innerHTML = a[b].hasAttribute("data-defaultText") ? a[b].getAttribute("data-defaultText") : "Core View"
  };
  return !0
};

随着有越来越多的高分辨率设备,所以依靠分辨率的这个方法也不灵了。

时间: 2024-09-17 04:23:18

检测桌面浏览器的初步想法的相关文章

移动浏览器和桌面浏览器在前几年的使用情况

新功能:全浏览器数据 这个项目添加了一个全新的功能.从现在起,数据将会包含所有对于桌面和移动的浏览器,和那些移动份额达到了至少20%的国家.这个季度中是尼日利亚和印度 在四五年中,浏览器种的统计数据显示了,主力的移动浏览器以及主力的桌面浏览器在市场争夺趋于种的常态化.这也告知了web开发者即将会有那些什么变化.我们又该做如何的应对呢. 概述 首先是一般性的概述,通常我们用所有网站访问量的移动份额来排序国家.南韩已经超过了美国成为榜首.英国的移动份额扩大了一倍,从5%上涨到10%. Opera现在

PHP 检测手机浏览器的代码

<?php                function is_mobile(){                    // returns true if one of the specified mobile browsers is detected                    $regex_match="/(nokiaiphoneandroidmotorola^mot\-softbankfomadocomokddiup\.browserup\.link";  

Opera桌面浏览器21中文版增加网址栏设置功能

炎夏降至,当手机浏览器已换上清爽夏装,你还能忍受一个臃肿的桌面浏览器吗?李奥纳多·达·芬奇曾说:"简单是终极的复杂."承袭北欧极简血统,Opera欧朋一直追求简洁的设计理念,致力于为用户带来高速.安全.有趣的浏览体验.提炼归纳用户需求,将复杂的技术藏在界面之后,这一次,欧朋告诉你--简洁,即是给用户最大的关爱. 2014年5月9日,北京,Opera欧朋首次面向中国大陆用户发布桌面浏览器-- Opera 桌面浏览器21中文版. "光环"萦绕 炫畅体验 本次在 Wind

Firefox插件让你在桌面浏览器体验Firefox OS

Mozilla推出的Firefox浏览器插件r2d2b2g现在已经变成一个Firefox OS模拟器,方便开发者和普通用户在桌面浏览器上体验Firefox OS.在其官方博客中,Mozilla表示希望该模拟器插件能更好地帮助开发者轻松创建Firefox OS的应用. 与此同时,开发者也不需要准备多个移动设备来安装试用自己的新应用. 使用方法: 1. 点击此处下载r2d2b2g插件,并完成安装.(下载回来的是一个后缀名为.xpi文件,只需打开Firefox浏览器,将文件拖拽至浏览器页面即可进行安装

Win7如何自动检测设置浏览器更新

  Win7如何自动检测设置浏览器更新 1.利用此策略设置,可管理Internet Explorer 是否在Internet中检查较新版本.如果将Internet Explorer 设置为执行上述操作,则会每隔大约30天执行一次检查,并且当有新版本可用时会提示用户安装新版本. 2.如果启用此策略设置,则Internet Explorer 会每隔大约30天在Internet中检查一次新版本,并在有新版本可用时提示用户下载新版本. 3.如果禁用此策略设置,则Internet Explorer 不会在

ie浏览器-JS检测IE浏览器的版本

问题描述 JS检测IE浏览器的版本 用JS检测IE浏览器的版本,非IE8弹出遮罩层(隐藏层),是IE8则不弹出,有大神能指导一下么 解决方案 var IeMsg="请使用ie8或ie9浏览器"; var flag = true; if(navigator.userAgent.indexOf("MSIE")>0) { if(navigator.userAgent.indexOf("MSIE 6.0")>0) { flag = false

html5-移动端网页检测到浏览器窗口尺寸问题

问题描述 移动端网页检测到浏览器窗口尺寸问题 我的手机屏幕分辨率是1920 * 1080,但我在网页中用window.innerHTML检测到 的手机尺寸是360 * 640. iPad mini2 检测到的尺寸是768 * 1024. 这是怎么回事? 解决方案 [JS]js代码来判断电脑或手机屏幕分辨率大小源代码 s = " 屏幕分辨率的高:"+ window.screen.height+"n"; s += " 屏幕分辨率的宽:"+ windo

javascript 特性检测并非浏览器检测

javascript 特性检测并非浏览器检测 详细出处参考:.net/article/21834.htm">http://www.111cn.net/article/21834.htm 起初前端工程师们就极力反对浏览器检测,他们认为类似user-agent嗅探的方法是很不好的,理由是它并不是一种面向未来的代码,无法适应新版的浏览器.更好的做法是使用特性检测,就像这样: 复制代码 代码如下: if (navigator.userAgent.indexOf("MSIE 7"

百度启动桌面浏览器产品研发

百度客户端副总监吴涛透露浏览器研发信息 1月12日下午消息,百度已经开始着手进行桌面浏览器产品的研发,并在百度公司内部就此进行 意见征集.与此同时,百度也已公开的招募相关产品经理等职位. 据悉,百度客户端副总监吴涛在百度说吧中征集对百度浏览器的意见,由此,百度正在研发桌面浏览器产品一事,才正式得以为外界所知. 吴涛当时透露,百度之所以要推出浏览器,"短期目标看,是为了更好的占领搜索流量入口:稍远点看,是希望把这个产品变成百度的应用平台,解决信息触达桌面能力.个性化信息服务等问题:再远点看,是要逐