Calcular o tempo total em primeiro plano

Este guia detalha como calcular com precisão o tempo total que um usuário passa visualizando ativamente uma página. As métricas tradicionais, como o tempo na página, geralmente incluem incorretamente o tempo gasto com a página em segundo plano. Ao usar a API VisibilityStateEntry, é possível medir apenas o "tempo em primeiro plano", fornecendo uma métrica melhor do engajamento do usuário.

Implementação do cálculo do tempo em primeiro plano

A API PerformanceTimeline expõe as mudanças de estado de visibilidade como entradas de desempenho. Em vez de reagir a eventos visibilitychange e acumular tempo manualmente durante uma sessão, você pode consultar todo o histórico de visibilidade a qualquer momento.

OBRIGATÓRIO: consulte as entradas de desempenho de visibility-state para calcular o tempo real em primeiro plano.

/**
 * Calculates total time the page was in the visible state.
 *
 * @returns {number} Total foreground time in milliseconds.
 */
function getTotalForegroundTime() {
  // MANDATORY: Query the visibility-state entries from the performance timeline.
  const entries = performance.getEntriesByType('visibility-state');

  // Fallback: If the browser does not support VisibilityStateEntry,
  // the API will gracefully return an empty array.
  if (entries.length === 0) {
    // Return total time since navigation start as a fallback.
    return performance.now();
  }

  let totalForegroundTime = 0;

  for (let i = 0; i < entries.length; i++) {
    // Only calculate duration for periods where the state was 'visible'
    if (entries[i].name === 'visible') {
      const start = entries[i].startTime;

      // The end time is the start time of the next state change,
      // or the current time if this is the final entry.
      const end = i + 1 < entries.length
          ? entries[i + 1].startTime
          : performance.now();

      totalForegroundTime += (end - start);
    }
  }

  return totalForegroundTime;
}

Substitutos e suporte ao navegador

A API VisibilityStateEntry é uma adição moderna à linha do tempo de performance e pode não ser compatível com todos os navegadores.

Como performance.getEntriesByType('visibility-state') retorna uma matriz vazia em navegadores sem suporte, a detecção de recursos é integrada ao fluxo de cálculo. Sempre verifique se as entradas são retornadas antes de continuar.

Se a API não for compatível, o substituto recomendado é retornar performance.now(). Isso representa o tempo total desde a navegação, que serve como um limite superior razoável para o tempo de engajamento quando o histórico de estado de visibilidade não está disponível.

const entries = performance.getEntriesByType('visibility-state');

// If the array is empty, the API is likely unsupported.
if (entries.length === 0) {
  // Fallback: Return total time since page load.
  return performance.now();
}