Skip to content
Snippets Groups Projects
exit-on-blur.js 1.76 KiB
Newer Older
/**
 * Emits an "exit" event when a user has stopped using the app for a certain period of time
 * @system exit-on-blur
 */
Robert Long's avatar
Robert Long committed
AFRAME.registerSystem("exit-on-blur", {
  init() {
    this.onBlur = this.onBlur.bind(this);
    this.onFocus = this.onFocus.bind(this);
    this.onTimeout = this.onTimeout.bind(this);
    this.onEnterVR = this.onEnterVR.bind(this);

    this.isOculusBrowser = navigator.userAgent.match(/Oculus/);
    this.enteredVR = false;
Robert Long's avatar
Robert Long committed

    window.addEventListener("blur", this.onBlur);
    window.addEventListener("focus", this.onFocus);
    this.el.addEventListener("enter-vr", this.onEnterVR);
Robert Long's avatar
Robert Long committed

    this.exitTimeout = null;
  },

    // This is a hack to detect when an Oculus Go user has taken off the headset and the headset has
    // entered standby mode. Currently Oculus Browser is not emitting a blur, vrdisplaydeactivate,
    // vrdisplayblur, visibilitychange, or vrdisplaypresentchange event, so we wait 15 seconds after
    // the last requestAnimationFrame callback to determine if the headset has gone into standby mode.
    // We also check that you have entered VR so that this timeout does not occur in the setup UI.
    if (this.isOculusBrowser && this.enteredVR) {
      clearTimeout(this.exitTimeout);
      this.exitTimeout = setTimeout(this.onTimeout, 15 * 1000);
    }
  },

  onEnterVR() {
    this.enteredVR = true;
  },

Robert Long's avatar
Robert Long committed
  onBlur() {
    if (this.el.isMobile) {
      clearTimeout(this.exitTimeout);
      this.exitTimeout = setTimeout(this.onTimeout, 30 * 1000);
Robert Long's avatar
Robert Long committed
    }
  },

  onFocus() {
    if (this.el.isMobile) {
      clearTimeout(this.exitTimeout);
    }
  },

  onTimeout() {
    this.el.dispatchEvent(new CustomEvent("exit"));
  },

Robert Long's avatar
Robert Long committed
  remove() {
    clearTimeout(this.exitTimeout);
    window.removeEventListener("blur", this.onBlur);
  }
});