PushizoDocs

Vue ile Pushizo Web SDK

Vue için birincil yol @pushizo/vue paketidir: app.use(PushizoPlugin, options) paylaşılan @pushizo/web örneğini tarayıcıda bir kez başlatır, bileşenler usePushizo() composable'ı üzerinden SDK'ya ve reaktif izin/abonelik…

Vue için birincil yol @pushizo/vue paketidir: app.use(PushizoPlugin, options) paylaşılan @pushizo/web örneğini tarayıcıda bir kez başlatır, bileşenler usePushizo() composable'ı üzerinden SDK'ya ve reaktif izin/abonelik durumuna erişir, Options API'de this.$pushizo kullanılabilir. Paket Vue 3 ve Vue 2.7 ile çalışır ve SSR güvenlidir (sunucuda init çağrılmaz). Nuxt 3 için yalnızca istemci tarafında çalışan bir plugin dosyası yeterlidir. Paketsiz (yalnızca @pushizo/web) kurulum bölüm 9'dadır.

1. Kurulum

npm install @pushizo/vue @pushizo/web

@pushizo/web eş bağımlılıktır (peerDependency); Vue ^3.2 veya ^2.7 gerekir.

Service worker site kökünde: Vite projelerinde public/PushizoSDKWorker.js, Nuxt'ta public/PushizoSDKWorker.js.

// public/PushizoSDKWorker.js
const apiUrl = new URL(self.location.href).searchParams.get('apiUrl') || 'https://api.pushizo.com';
importScripts(`${apiUrl.replace(/\/$/, '')}/sdk-web/PushizoSDKWorker.js`);

Ortam: VITE_HS_APP_ID, VITE_HS_API_URL (Nuxt: NUXT_PUBLIC_HS_APP_ID, NUXT_PUBLIC_HS_API_URL → runtimeConfig.public).

2. Eklenti ve composable

// src/main.ts (Vue 3)
import { createApp } from 'vue';
import { PushizoPlugin } from '@pushizo/vue';
import App from './App.vue';

createApp(App)
  .use(PushizoPlugin, {
    appId: import.meta.env.VITE_HS_APP_ID,
    apiUrl: import.meta.env.VITE_HS_API_URL,
    serviceWorkerPath: '/PushizoSDKWorker.js',
    allowLocalhostAsSecureOrigin: import.meta.env.DEV,
    bell: { enabled: true },
  })
  .mount('#app');

Vue 2.7: Vue.use(PushizoPlugin, { appId: … }). Eklenti birden çok kez kurulsa da SDK bir kez başlatılır; yalnızca ilk seçenekler kullanılır. init hatası fırlatılmaz, usePushizo().error ref'ine yazılır.

usePushizo() şunları döndürür (ref'ler salt okunurdur):

AlanAçıklama
pushizoPaylaşılan SDK örneği (login, User, Notifications, Session, InAppMessages, Inbox …)
ready, errorinit tamamlandı / hata
permission'default' | 'granted' | 'denied' | 'unsupported'
pushSubscription{ id, token, optedIn, permission }
stateTüm durum tek ref'te

onNotificationClick(handler) bildirim tıklaması dinleyicisi ekler ve bileşen (ya da effectScope) sonlanınca kaldırır. Durum web SDK gözlemcilerinden beslenir; Vue 3'te uygulama sökülünce (app.unmount()) gözlemciler kaldırılır.

Nuxt 3

// plugins/pushizo.client.ts — yalnızca istemcide çalışır
import { PushizoPlugin } from '@pushizo/vue';

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig();
  nuxtApp.vueApp.use(PushizoPlugin, {
    appId: config.public.hsAppId,
    apiUrl: config.public.hsApiUrl,
    allowLocalhostAsSecureOrigin: import.meta.dev,
  });
});

Eklenti sunucuda kurulsa da SDK'ya dokunmaz; ready false kalır ve SDK'ya dokunan kod ready olana kadar çalışmaz. usePushizo() kullanan bileşenler sunucuda da çizileceğinden eklentiyi .client.ts yerine evrensel plugin olarak (plugins/pushizo.ts) kurmak da güvenlidir.

3. İzin ve abonelik

<script setup lang="ts">
import { usePushizo } from '@pushizo/vue';

const { pushizo, ready, error, permission, pushSubscription } = usePushizo();
</script>

<template>
  <p v-if="error" role="alert">{{ error.message }}</p>
  <p v-else-if="!ready">SDK yükleniyor…</p>
  <p v-else-if="permission === 'unsupported'">Bu tarayıcı web push desteklemiyor (HTTPS gerekir).</p>
  <p v-else-if="permission === 'denied'">Bildirimler tarayıcı ayarlarından engellenmiş.</p>
  <button v-else-if="pushSubscription.optedIn" type="button" @click="pushizo.User.pushSubscription.optOut()">Bildirimleri kapat</button>
  <button v-else type="button" @click="pushizo.Notifications.requestPermission()">Bildirimlere izin ver</button>
</template>

permission, istem sonucu ve (Permissions API destekleyen tarayıcılarda) site ayarlarından yapılan değişikliklerle güncellenir.

4. Login / logout

// Pinia store'unuzdaki kullanıcı değişince
import { watch } from 'vue';
import { usePushizo } from '@pushizo/vue';

const { pushizo, ready } = usePushizo();
watch(
  [ready, () => auth.user],
  ([isReady, user]) => {
    if (!isReady) return;
    if (user) void pushizo.login(user.id, user.identityHash); // identity_hash sunucudan (zorunluysa)
    else if (pushizo.User.externalId) void pushizo.logout();
  },
  { immediate: true },
);

5. Tag, olay ve rota takibi

pushizo.User.addTags({ plan: 'pro' });
pushizo.User.removeTag('plan');
pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9);

Vue Router ile in-app screen tetiği:

// src/router.ts
import { usePushizo } from '@pushizo/vue';

router.afterEach((to) => {
  const { pushizo, ready } = usePushizo();
  if (ready.value) pushizo.InAppMessages.setScreen(to.name ? String(to.name) : to.path);
});

usePushizo() inject kullanmaz (tek SDK örneği modül düzeyinde paylaşılır); router guard'ı gibi bileşen dışı yerlerde de çağrılabilir, yeter ki eklenti önce kurulmuş olsun.

6. Bildirim kutusu bileşeni

<script setup lang="ts">
import { onUnmounted, ref, watch } from 'vue';
import type { InboxItem } from '@pushizo/web';
import { usePushizo } from '@pushizo/vue';

const { pushizo, ready } = usePushizo();
const items = ref<InboxItem[]>([]);
const unread = ref(0);
const loading = ref(false);
const error = ref<string | null>(null);
let stop: (() => void) | null = null;

async function load() {
  loading.value = true;
  try {
    const page = await pushizo.Inbox.list({ limit: 20 });
    items.value = page.items;
    unread.value = page.unreadCount;
    error.value = null;
  } catch (e) {
    error.value = e instanceof Error ? e.message : String(e);
  } finally {
    loading.value = false;
  }
}
async function markRead(id: string) {
  const updated = await pushizo.Inbox.markRead(id);
  items.value = items.value.map((i) => (i.id === id ? updated : i));
}
async function archive(id: string) {
  await pushizo.Inbox.archive(id);
  items.value = items.value.filter((i) => i.id !== id);
}

watch(ready, (r) => { if (r) { void load(); stop = pushizo.Inbox.addObserver((e) => { unread.value = e.unreadCount; }); } }, { immediate: true });
onUnmounted(() => stop?.());
</script>

<template>
  <section aria-label="Bildirim kutusu">
    <h2>Bildirimler ({{ unread }} okunmamış)</h2>
    <button type="button" :disabled="loading" @click="load">{{ loading ? 'Yükleniyor…' : 'Yenile' }}</button>
    <button type="button" @click="pushizo.Inbox.markAllRead().then(load)">Tümünü okundu işaretle</button>
    <p v-if="error" role="alert">{{ error }}</p>
    <p v-else-if="items.length === 0">Bildirim yok.</p>
    <ul v-else>
      <li v-for="item in items" :key="item.id" :data-read="item.read">
        <strong>{{ item.title ?? '(başlıksız)' }}</strong>
        <p v-if="item.body">{{ item.body }}</p>
        <a v-if="item.url" :href="item.url">Aç</a>
        <button type="button" :disabled="item.read" @click="markRead(item.id)">Okundu</button>
        <button type="button" @click="archive(item.id)">Arşivle</button>
      </li>
    </ul>
  </section>
</template>

7. Bildirim tıklaması

import { onNotificationClick } from '@pushizo/vue';

// setup içinde: bileşen sökülünce kendiliğinden kaldırılır
onNotificationClick(({ notification, result }) => {
  router.push(result.url ?? notification.url ?? '/');
});

8. Sorun giderme

  • window is not defined: @pushizo/web'i sunucuda doğrudan çağırmayın; @pushizo/vue eklentisi sunucuda init çağırmaz.
  • usePushizo: önce app.use(PushizoPlugin, …) hatası: eklenti kurulmadan composable çağrıldı.
  • Service worker 404 / abonelik oluşmuyor / bildirim gelmiyor: Web SDK sorun giderme.
  • iOS Safari: iOS web push.

9. Alternatif: paketsiz kurulum

@pushizo/vue kullanmadan yalnızca npm install @pushizo/web ile kendi eklentinizi yazabilirsiniz (yukarıdaki bölümlerde usePushizo() yerine bu dosyadaki usePushizo() → { sdk, ready, error, subscription } kullanılır):

// src/pushizo.ts
import { inject, ref, type App, type InjectionKey, type Ref } from 'vue';
import Pushizo, { type PushizoSdk, type InitOptions, type PushSubscriptionState } from '@pushizo/web';

export interface PushizoState {
  sdk: PushizoSdk;
  ready: Ref<boolean>;
  error: Ref<string | null>;
  subscription: Ref<PushSubscriptionState | null>;
}

export const PushizoKey: InjectionKey<PushizoState> = Symbol('pushizo');

export function createPushizo(options: InitOptions) {
  const ready = ref(false);
  const error = ref<string | null>(null);
  const subscription = ref<PushSubscriptionState | null>(null);

  return {
    install(app: App) {
      app.provide(PushizoKey, { sdk: Pushizo, ready, error, subscription });
      if (typeof window === 'undefined') return; // SSR: tarayıcı API'sine dokunma
      Pushizo.User.pushSubscription.addObserver((state) => { subscription.value = state; });
      Pushizo.init(options)
        .then(() => {
          ready.value = true;
          subscription.value = Pushizo.User.pushSubscription.state;
        })
        .catch((err: unknown) => { error.value = err instanceof Error ? err.message : String(err); });
    },
  };
}

export function usePushizo(): PushizoState {
  const state = inject(PushizoKey);
  if (!state) throw new Error('usePushizo, createPushizo plugin’i kurulmadan kullanılamaz');
  return state;
}
// src/main.ts
createApp(App)
  .use(createPushizo({ appId: import.meta.env.VITE_HS_APP_ID, apiUrl: import.meta.env.VITE_HS_API_URL, serviceWorkerPath: '/PushizoSDKWorker.js' }))
  .mount('#app');

Bu yolda izin değişimi kendiliğinden yansımaz (Pushizo.Notifications.addPermissionObserver ekleyin) ve usePushizo() inject kullandığından bileşen/setup dışında app.runWithContext(() => usePushizo()) gerekir.

10. Özellik bayrakları, içerik kartları ve site araması

Composable'lar Web SDK'nın gözlemci ve görünüm API'lerini bileşen kapsamına bağlar: kapsam sonlanınca gözlemciler kaldırılır (FeatureFlags.removeObserver, Inbox.removeObserver, Notifications.removeForegroundLifecycleListener), içerik kartı görünümü destroy() edilir.

<script setup lang="ts">
import { ref } from 'vue';
import {
  onNotificationForeground,
  useContentCards,
  useFeatureFlag,
  useFeatureFlagValue,
  useInboxUnreadCount,
  usePushizoSearch,
} from '@pushizo/vue';

const newCheckout = useFeatureFlag('new_checkout'); // bayraklar yenilenince güncellenir
const limit = useFeatureFlagValue<number>('cart_limit', 5);
const unread = useInboxUnreadCount(); // null: henüz bilinmiyor
const { response, loading, error, search, trackClick } = usePushizoSearch();

const cards = ref<HTMLElement | null>(null);
useContentCards(cards, { theme: 'auto', limit: 20 }); // öğe bağlanıp SDK hazır olunca çizilir

onNotificationForeground((e) => {
  if (document.visibilityState === 'visible') e.preventDefault();
});
</script>

<template>
  <span>Bildirimler<template v-if="unread"> ({{ unread }})</template></span>
  <p v-if="newCheckout">Yeni ödeme akışı açık (limit {{ limit }})</p>

  <input type="search" @input="search(($event.target as HTMLInputElement).value, { limit: 5 })" />
  <p v-if="loading">Aranıyor…</p>
  <p v-if="error" role="alert">Arama yapılamadı.</p>
  <ul>
    <li v-for="(r, i) in response?.results ?? []" :key="r.id">
      <a :href="r.url" @click="trackClick(r.url, i + 1)">{{ r.title }}</a>
    </li>
  </ul>

  <div ref="cards" class="cards" />
</template>
  • useFeatureFlag / useFeatureFlagValue: SDK hazır olana kadar ve sunucuda defaultValue döner; setup içinde çağrılmalıdır.
  • useContentCards: { error, refresh } döndürür; görünüm betiği tembel yüklenir. Paketleyiciyle gömmek için { mount: mountContentCards } (import { mountContentCards } from '@pushizo/web/content-cards').
  • usePushizoSearch: art arda aramalarda yalnızca son aramanın yanıtı yazılır; boş metin durumu temizler. Hazır arama penceresi için pushizo.Search.open().
  • Profille giriş (pushizo.login('user_42', undefined, { email, tags })), rozet (pushizo.Notifications.setBadgeCount(3)), konum izni (pushizo.Location.permissionGranted), özel in-app çizimi (pushizo.InAppMessages.setRenderer) ve sohbet (pushizo.Chat.getConfig() …) usePushizo().pushizo ile doğrudan kullanılır.

Bu sayfada