Skip to content

Page visibility

Allows tracking window focus and blur with Events and Stores.

INFO

Uses Page Visibility API under the hood

Usage

All you need to do is to create an integration by calling trackPageVisibility with an integration options:

  • setup: after this Event all listeners will be installed, and the integration will be ready to use; it is required because it is better to use explicit initialization Event in the application.
  • teardown?: after this Event all listeners will be removed, and the integration will be ready to be destroyed.
ts
import { trackPageVisibility } from '@withease/web-api';

const { visible, hidden, $visible, $hidden } = trackPageVisibility({
  setup: appStarted,
});

Returns an object with:

  • visible: Event fired when the content of a tab has become visible
  • hidden: Event fired when the content of a tab has been hidden
  • $visible: Store with true if document is visible and false if it is hidden
  • $hidden: Store with false if document is visible and true if it is hidden

TIP

It supports @@trigger protocol. Since it allows firing only one Event trackPageVisibility triggers visible as a fired in case of @@trigger protocol.

ts
import { trackPageVisibility } from '@withease/web-api';

somethingExpectsTrigger(trackPageVisibility);

Live demo

Let us show you a live demo of how it works. The following demo displays history of hidden and visible Events. Switch to other tab and return there see how it works.

<script setup>
import { trackPageVisibility } from '@withease/web-api';
import { createEvent, createStore } from 'effector';
import { useUnit } from 'effector-vue/composition';
import { onMounted } from 'vue';

const appStarted = createEvent();

const { visible, hidden } = trackPageVisibility({ setup: appStarted });

const $history = createStore([])
  .on(visible, (state) => [...state, { at: new Date(), action: 'visible' }])
  .on(hidden, (state) => [...state, { at: new Date(), action: 'hidden' }]);

const history = useUnit($history);

onMounted(appStarted);
</script>

<template>
  <p>Event's history:</p>

  <ul>
    <li v-for="event in history">
      {{ event.action }} at {{ event.at.toLocaleTimeString() }}
    </li>
  </ul>

  <span v-if="history.length === 0">No events yet</span>
</template>

Released under the MIT License.