简体   繁体   中英

How to detect if the React app is actually being viewed on mobile menu actions

I have a React app, I've added eventlisteners to the window. So, this way I can detect if the user actually viewing the page or not. On computer browser, everything works as expected.

But I tried this on IphoneX (it's irrelevant but the browser was Safari), and I came across this: If the user holds the bottom of the menu and swipe away all the open ones , then onBlur doesn't work . It stays on the onFocus event. So actually window.eventlistener not working properly on mobile.

Also, when I open the browser again (but not clicking anything, just opening the browser and view the page) onFocus event also not working. It waits for me to touch or click somewhere on the page.

How to handle user focus/blur completely on mobile side?

In the documentation for iOS / Safari supported events, they suggest pageshow and pagehide to listen for the kind of activity that I think you're talking about.

You can use requestAnimationFrame to check if the user is watching the page.

function isWatching(){
        console.log("watching: " + Date.now());
    requestAnimationFrame(isWatching);
}
requestAnimationFrame(isWatching);

See the example here: https://jsfiddle.net/t2r1sp56/ and you should also read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

you can use window.navigator to get all OS and browser info

You can use visibilityChange event and for the complete compatibility, you need to use webkit, ms, etc. prefix. I hope it helps:)

 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) }

I have solved the issue using below event listeners.

document.addEventListener("visibilitychange", handleActivity);
document.addEventListener("blur", handleActivityFalse);
window.addEventListener("blur", handleActivityFalse);
window.addEventListener("focus", handleActivityTrue);
document.addEventListener("focus", handleActivityTrue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM