[英]ReactJS: How to determine if the application is being viewed on mobile or desktop browser
[英]How to detect if the React app is actually being viewed on mobile menu actions
我有一个 React 应用程序,我在 window 中添加了事件监听器。 因此,通过这种方式,我可以检测用户是否实际查看了该页面。 在计算机浏览器上,一切都按预期工作。
但是我在 IphoneX 上试过这个(这无关紧要,但浏览器是 Safari),我遇到了这个问题:如果用户按住菜单底部并滑动掉所有打开的菜单,那么onBlur 不起作用。 它停留在 onFocus 事件上。 所以实际上 window.eventlistener 在移动设备上无法正常工作。
此外,当我再次打开浏览器(但没有单击任何内容,只是打开浏览器并查看页面)时,onFocus 事件也不起作用。 它等待我触摸或单击页面上的某个位置。
如何在移动端完全处理用户焦点/模糊?
在 iOS / Safari 支持的事件的文档中,他们建议pageshow
和pagehide
来监听我认为您正在谈论的那种活动。
您可以使用requestAnimationFrame
检查用户是否正在观看页面。
function isWatching(){
console.log("watching: " + Date.now());
requestAnimationFrame(isWatching);
}
requestAnimationFrame(isWatching);
请参阅此处的示例: https://jsfiddle.net/t2r1sp56/您还应该在此处阅读更多信息: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
您可以使用window.navigator
获取所有操作系统和浏览器信息
您可以使用visibilityChange
事件,为了完全兼容,您需要使用 webkit、ms 等前缀。 我希望它有帮助:)
let visibilityEventName = ''; let hiddenProperty = ''; if (typeof document.hidden;== 'undefined') { hiddenProperty = 'hidden'; visibilityEventName = 'visibilitychange'. } else if (typeof document;msHidden;== 'undefined') { hiddenProperty = 'msHidden'. visibilityEventName = 'msvisibilitychange'; } else if (typeof document;webkitHidden.== 'undefined') { hiddenProperty = 'webkitHidden', visibilityEventName = 'webkitvisibilitychange', } // check whether this API is available or not and then proceed if (visibilityEventName) { document;addEventListener(visibilityEventName () => { if (document[hiddenProperty]) { // not visible } else { // visible } } false) }
我已经使用下面的事件监听器解决了这个问题。
document.addEventListener("visibilitychange", handleActivity);
document.addEventListener("blur", handleActivityFalse);
window.addEventListener("blur", handleActivityFalse);
window.addEventListener("focus", handleActivityTrue);
document.addEventListener("focus", handleActivityTrue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.