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

Viewed 296

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?

5 Answers

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 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);
Related