SAP UI5 设备类型检测 Device API 的工作原理
source link: https://blog.51cto.com/jerrywangsap/5115711
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
SAP UI5 设备类型检测 Device API 的工作原理
原创为什么 SAP UI5 应用初始化时,要调用 SAP UI5 设备检测 API,即 sap.ui.Device
来检测运行当前 SAP UI5 应用的设备类型?
可以查看我这篇文章: SAP UI5 应用开发教程之三十四 - SAP UI5 应用基于设备类型的页面适配功能(Device Adaptation)。
本文介绍该设备检测 API 本身的工作原理。
Device API 所在的 Device.js 文件被加载后,立即执行 setOS
方法:
从 OS
结构变量可以看出,SAP UI5 支持下列几种操作系统的检测:
- Android
- Linux
- Windows
我们通过浏览器的 userAgent
来判断操作系统类型:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
使用正则表达式匹配,如果发现有 Android 字符串,则说明当前的 SAP UI5 应用,运行在 Android 移动设备上。
如果没有检测到,进入 getDesktopOS
分支。
我用的是 Windows10 操作系统,platform 字段值为 Win32
:
成功解析出操作系统的版本号为 10:
给 Device API 里的 device 对象设置对应的 os 值:
然后执行 setBrowser
设置浏览器对应的 flag:
基于 webkit
和 mozilla
的浏览器类型检测,使用下面的正则表达式完成:
var rwebkit = /(webkit)[ \/]([\w.]+)/;
var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;
最后仍然通过正则表达式结合 userAgent
,检测出我在 Windows10 操作系统上使用的浏览器类型为 Chrome
:
根据这个 StackOverflow 帖子 提到的如何检测 Chrome 是否使用了 blink
渲染引擎的实现:
给 Device 全局变量的 support 字段赋值:
进入设备类型检测:
首先检测是否是 tablet
:
var bTabletDetected = !!isTablet(customUA);
从这里能够看出,SAP UI5 判断一个设备是 tablet
的逻辑为,如果该设备的操作系统是 windows 或者 mac 或者 Linux,那么如果它支持 touch
操作,就被看成是 tablet
:
从下图代码,我们终于找到了 SAP UI5 判定当前 device 是 phone
的逻辑:如果设备支持 touch
操作并且不是 tablet
,那么一定是 phone
.
而检测一台设备是否支持 touch 的逻辑:
var detectTouch = function () {
return !!(('ontouchstart' in window)
|| (window.navigator.maxTouchPoints > 0)
|| (window.DocumentTouch && document instanceof window.DocumentTouch)
|| (window.TouchEvent && Device.browser.firefox));
};
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK