Pular para o conteúdo principal
Zenovay
Gratuito20 minutesIntermediário

Integração com Framework Personalizado

Integre o Zenovay com qualquer framework JavaScript — vanilla JS, Svelte, Angular e implementações personalizadas. Explore a configuração de integração e as melhores práticas.

integrationjavascriptcustomvanilla-jssvelte
Última atualização:

Integre o analytics do Zenovay em qualquer framework JavaScript ou aplicação vanilla JavaScript usando nossa API de rastreamento flexível.

Instalação Universal do Script

Tag de Script Básica

Funciona com qualquer framework:

<script
  defer
  data-tracking-code="YOUR_TRACKING_CODE"
  src="https://api.zenovay.com/z.js"
></script>

Atributos do Script

AtributoDescrição
data-tracking-codeObrigatório. O código de rastreamento do seu site
deferRecomendado. Carrega o script sem bloquear a renderização da página

Configuração Padrão

<script
  defer
  data-tracking-code="YOUR_TRACKING_CODE"
  src="https://api.zenovay.com/z.js"
></script>

Vanilla JavaScript

Uso Básico

// Rastrear um evento
window.zenovay('track', 'button_click', {
  button_id: 'signup',
  location: 'hero'
});

// Rastrear visualização de página (se auto-track desativado)
window.zenovay('page');

// Identificar um usuário
window.zenovay('identify', 'user-123', {
  email: '[email protected]',
  plan: 'pro'
});

// Rastrear uma meta
window.zenovay('goal', 'purchase', {
  value: 99.99
});

// Rastrear receita
window.zenovay('revenue', 149.99, 'USD', {
  order_id: 'ORD-001'
});

Aguardar o Carregamento do Script

function waitForZenovay(callback, maxWait = 5000) {
  const startTime = Date.now();

  function check() {
    if (window.zenovay) {
      callback(window.zenovay);
    } else if (Date.now() - startTime < maxWait) {
      requestAnimationFrame(check);
    }
  }

  check();
}

// Uso
waitForZenovay((zenovay) => {
  zenovay('track', 'app_ready');
});

Padrão de Fila de Eventos

// Função de fila (funciona antes do carregamento do script)
window.zenovay = window.zenovay || function() {
  (window.zenovay.q = window.zenovay.q || []).push(arguments);
};

// Agora você pode chamar zenovay() imediatamente, mesmo antes do script carregar
window.zenovay('track', 'early_event', { source: 'inline' });
window.zenovay('page');

Integração com Svelte

Configuração no App.svelte

<script>
  import { onMount } from 'svelte';
  import { page } from '$app/stores';

  onMount(() => {
    // Rastrear visualização de página inicial
    if (window.zenovay) {
      window.zenovay('page');
    }
  });

  // Rastrear mudanças de rota
  $: if ($page && window.zenovay) {
    window.zenovay('page');
  }
</script>

Store do Svelte

// stores/analytics.js
import { writable } from 'svelte/store';

function createAnalyticsStore() {
  const { subscribe } = writable(null);

  return {
    subscribe,
    track: (event, data) => {
      if (typeof window !== 'undefined' && window.zenovay) {
        window.zenovay('track', event, data);
      }
    },
    identify: (userId, properties) => {
      if (typeof window !== 'undefined' && window.zenovay) {
        window.zenovay('identify', userId, properties);
      }
    },
    trackGoal: (name, value) => {
      if (typeof window !== 'undefined' && window.zenovay) {
        window.zenovay('goal', name, { value });
      }
    }
  };
}

export const analytics = createAnalyticsStore();

Uso em Componentes Svelte

<script>
  import { analytics } from '../stores/analytics';

  function handleClick() {
    analytics.track('button_click', { button: 'cta' });
  }
</script>

<button on:click={handleClick}>
  Clique Aqui
</button>

Integração com SvelteKit

// hooks.client.js
import { page } from '$app/stores';

page.subscribe(($page) => {
  if (typeof window !== 'undefined' && window.zenovay && $page) {
    window.zenovay('page');
  }
});

Integração com Angular

Criação do Serviço

// analytics.service.ts
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

declare global {
  interface Window {
    zenovay: {
      (command: 'track', event: string, data?: Record<string, any>): void;
      (command: 'page'): void;
      (command: 'goal', name: string, data?: Record<string, any>): void;
      (command: 'revenue', amount: number, currency: string, meta?: Record<string, any>): void;
      (command: 'identify', userId: string, properties?: Record<string, any>): void;
    };
  }
}

@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {
  constructor(private router: Router) {
    this.setupRouteTracking();
  }

  private setupRouteTracking() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
      this.trackPageview(event.urlAfterRedirects);
    });
  }

  track(event: string, data?: Record<string, any>) {
    if (window.zenovay) {
      (window as any).zenovay('track', event, data);
    }
  }

  trackPageview() {
    if (window.zenovay) {
      (window as any).zenovay('page');
    }
  }

  trackGoal(name: string, value?: number) {
    if (window.zenovay) {
      (window as any).zenovay('goal', name, { value });
    }
  }

  identify(userId: string, properties?: Record<string, any>) {
    if (window.zenovay) {
      (window as any).zenovay('identify', userId, properties);
    }
  }
}

Uso em Componentes

// signup.component.ts
import { Component } from '@angular/core';
import { AnalyticsService } from './analytics.service';

@Component({
  selector: 'app-signup',
  template: `<button (click)="handleSignup()">Cadastre-se</button>`
})
export class SignupComponent {
  constructor(private analytics: AnalyticsService) {}

  handleSignup() {
    this.analytics.track('signup_click', {
      source: 'header'
    });
  }
}

Configuração do Módulo

// app.module.ts
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { AnalyticsService } from './analytics.service';

export function initAnalytics(analytics: AnalyticsService) {
  return () => {
    // Inicializar rastreamento
  };
}

@NgModule({
  providers: [
    AnalyticsService,
    {
      provide: APP_INITIALIZER,
      useFactory: initAnalytics,
      deps: [AnalyticsService],
      multi: true
    }
  ]
})
export class AppModule {}

Integração com Ember.js

Criação do Serviço

// app/services/analytics.js
import Service from '@ember/service';
import { inject as service } from '@ember/service';

export default class AnalyticsService extends Service {
  @service router;

  constructor() {
    super(...arguments);
    this.setupRouteTracking();
  }

  setupRouteTracking() {
    this.router.on('routeDidChange', () => {
      this.trackPageview(this.router.currentURL);
    });
  }

  track(event, data) {
    if (window.zenovay) {
      window.zenovay('track', event, data);
    }
  }

  trackPageview() {
    if (window.zenovay) {
      window.zenovay('page');
    }
  }

  identify(userId, properties) {
    if (window.zenovay) {
      window.zenovay('identify', userId, properties);
    }
  }
}

Integração com Alpine.js

<div x-data="{ analytics: $store.analytics }">
  <button @click="analytics.track('click', { button: 'cta' })">
    Clique Aqui
  </button>
</div>

<script>
document.addEventListener('alpine:init', () => {
  Alpine.store('analytics', {
    track(event, data) {
      if (window.zenovay) {
        window.zenovay('track', event, data);
      }
    },
    identify(userId, properties) {
      if (window.zenovay) {
        window.zenovay('identify', userId, properties);
      }
    }
  });
});
</script>

Integração com jQuery

// Inicializar helper de rastreamento
$.zenovay = {
  track: function(event, data) {
    if (window.zenovay) {
      window.zenovay('track', event, data);
    }
  },
  identify: function(userId, properties) {
    if (window.zenovay) {
      window.zenovay('identify', userId, properties);
    }
  }
};

// Uso
$(document).ready(function() {
  $('#signup-btn').click(function() {
    $.zenovay.track('signup_click', {
      button: $(this).data('name')
    });
  });
});

Web Components

// analytics-tracker.js
class AnalyticsTracker extends HTMLElement {
  connectedCallback() {
    this.addEventListener('click', this.handleClick.bind(this));
  }

  handleClick() {
    const event = this.getAttribute('data-event');
    const dataAttrs = {};

    for (const attr of this.attributes) {
      if (attr.name.startsWith('data-prop-')) {
        const key = attr.name.replace('data-prop-', '');
        dataAttrs[key] = attr.value;
      }
    }

    if (window.zenovay && event) {
      window.zenovay('track', event, dataAttrs);
    }
  }
}

customElements.define('analytics-tracker', AnalyticsTracker);

Uso:

<analytics-tracker
  data-event="cta_click"
  data-prop-button="hero"
  data-prop-page="home"
>
  <button>Começar</button>
</analytics-tracker>

Padrões para Single Page Applications (SPA)

Rastreamento com History API

// Rastrear mudanças no histórico
(function() {
  const pushState = history.pushState;
  const replaceState = history.replaceState;

  history.pushState = function() {
    pushState.apply(history, arguments);
    trackPageChange();
  };

  history.replaceState = function() {
    replaceState.apply(history, arguments);
    trackPageChange();
  };

  window.addEventListener('popstate', trackPageChange);

  function trackPageChange() {
    if (window.zenovay) {
      // Pequeno delay para garantir que o DOM foi atualizado
      setTimeout(() => {
        window.zenovay('page');
      }, 100);
    }
  }
})();

Roteamento Baseado em Hash

window.addEventListener('hashchange', function() {
  if (window.zenovay) {
    window.zenovay('page');
  }
});

Definições TypeScript

// types/zenovay.d.ts
interface ZenovayEventData {
  [key: string]: string | number | boolean | undefined;
}

interface ZenovayRevenueData {
  order_id: string;
  value: number;
  currency?: string;
  items?: Array<{
    id: string;
    name: string;
    price: number;
    quantity: number;
  }>;
}

interface Zenovay {
  (command: 'track', event: string, data?: ZenovayEventData): void;
  (command: 'page'): void;
  (command: 'goal', name: string, data?: { value?: number }): void;
  (command: 'revenue', amount: number, currency: string, meta?: Record<string, unknown>): void;
  (command: 'identify', userId: string, properties?: ZenovayEventData): void;
}

declare global {
  interface Window {
    zenovay?: Zenovay;
  }
}

export {};

Padrão de Biblioteca Wrapper

Crie um wrapper reutilizável:

// lib/analytics.ts
class Analytics {
  private queue: Array<() => void> = [];
  private ready = false;

  constructor() {
    this.waitForScript();
  }

  private waitForScript() {
    const check = () => {
      if (window.zenovay) {
        this.ready = true;
        this.processQueue();
      } else {
        requestAnimationFrame(check);
      }
    };
    check();
  }

  private processQueue() {
    this.queue.forEach(fn => fn());
    this.queue = [];
  }

  private execute(fn: () => void) {
    if (this.ready) {
      fn();
    } else {
      this.queue.push(fn);
    }
  }

  track(event: string, data?: Record<string, any>) {
    this.execute(() => (window.zenovay as any)('track', event, data));
  }

  pageview() {
    this.execute(() => (window.zenovay as any)('page'));
  }

  identify(userId: string, properties?: Record<string, any>) {
    this.execute(() => (window.zenovay as any)('identify', userId, properties));
  }

  goal(name: string, value?: number) {
    this.execute(() => (window.zenovay as any)('goal', name, { value }));
  }

  revenue(amount: number, currency: string, meta?: Record<string, any>) {
    this.execute(() => (window.zenovay as any)('revenue', amount, currency, meta));
  }
}

export const analytics = new Analytics();

Testando Sua Integração

Modo Debug

Ative a registro de debug para ver a atividade do rastreador no console do navegador. Há três formas de ativar:

<!-- 1. Adicione o atributo data-debug à tag de script -->
<script
  defer
  data-tracking-code="YOUR_TRACKING_CODE"
  data-debug="true"
  src="https://api.zenovay.com/z.js"
></script>
2. Acrescente ?zenovay_debug=true a qualquer URL de página (útil para produção).
3. O registro de debug está ativado automaticamente ao executar em localhost.

Com o debug ativado, o rastreador registra cada evento que envia no console.

Etapas de Verificação

  1. Abra o DevTools do navegador
  2. Vá para a aba Rede (Network)
  3. Filtre por "zenovay" ou "analytics"
  4. Execute ações
  5. Verifique se as requisições foram enviadas

Evento de Teste

// Teste rápido
if (window.zenovay) {
  window.zenovay('track', 'test_event', {
    test: true,
    timestamp: Date.now()
  });
  console.log('Evento de teste enviado');
} else {
  console.error('Zenovay não está carregado');
}

Solução de Problemas

Script Não Carregando

Verifique:

  • URL do script está correta
  • Sem interferência de bloqueadores de anúncios
  • ID do site válido
  • Requisições de rede visíveis

Eventos Não Rastreando

Verifique:

  • Se window.zenovay existe
  • Se o formato dos dados está correto
  • Se não há erros de JavaScript
  • Se o domínio está permitido

Problemas de Navegação em SPA

Certifique-se de:

  • Que as mudanças de rota são detectadas
  • Que trackPageview é chamado na navegação
  • Que não há rastreamento duplicado

Próximos Passos

Este artigo foi útil?