PushizoDocs
SDK guides

Web SDK

@pushizo/web for browser push (Chrome, Edge, Firefox, Safari 16.4+), email/SMS subscriptions, in-app messages and the notification inbox.

The Web SDK runs in the browser: permission prompts, Web Push subscriptions (VAPID), user/tag/alias management, email/SMS collection, events, in-app messages and the notification inbox. Push requires HTTPS (localhost is exempt). The package is @pushizo/web; the CDN build is served by the API server as /sdk-web/PushizoSDK.js. Framework guides: React, Vue, Angular; iOS Safari PWA: iOS web push.

Installation

Script tag

<script src="https://api.pushizo.com/sdk-web/PushizoSDK.js" async></script>
<script>
  window.PushizoDeferred = window.PushizoDeferred || [];
  PushizoDeferred.push(async (Pushizo) => {
    await Pushizo.init({ appId: 'app_…', apiUrl: 'https://api.pushizo.com' });
  });
</script>

npm (ESM)

npm install @pushizo/web
import Pushizo from '@pushizo/web';
await Pushizo.init({ appId: 'app_…', apiUrl: 'https://api.pushizo.com' });

The SDK only runs in the browser; in SSR frameworks, initialize it inside a client component or useEffect.

Service worker

PushizoSDKWorker.js at the root of your site:

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

If you already have a service worker, add the same importScripts line to it and pass its path with serviceWorkerPath. If the file is not at the root, the server must send the Service-Worker-Allowed: / header.

init options

OptionDefaultDescription
appId—Required
apiUrlOrigin the SDK was loaded fromAPI root; if omitted (or set to the global root), the SDK switches to the regional root via config api_url, while a custom URL is preserved; 421 HS_WRONG_CELL is followed in every case (see SDK overview → Regional API URL)
serviceWorkerPath / serviceWorkerScope/PushizoSDKWorker.js / /SW path and scope
allowLocalhostAsSecureOriginfalseAllow running on HTTP localhost (development)
requiresPrivacyConsentfalseNo network calls until setConsentGiven(true) is called
autoResubscribetrueIf permission is granted, create/refresh the subscription automatically on load
autoPromptfalseOpen the browser's native prompt on load (respects the backoff schedule)
slidedownoff{ enabled, collect?, delaySeconds, pageViews, retryDays, title, message, acceptText, cancelText, emailLabel?, smsLabel? }; collect: 'push' | 'email' | 'sms' | 'email_sms'
welcomeNotificationon{ disable?, title?, message?, url? } — local welcome notification after the first subscription
notificationClickHandlerMatchexactexact: a tab on the same URL, origin: a tab on the same origin
notificationClickHandlerActionnavigateIn the matching tab, navigate goes to the URL, focus only brings it to the front
promptOptions—{ customlink?, backoffDays? } — custom link prompt and backoff schedule (default [3, 7, 30] days)
belloff{ enabled, position: 'bottom-right' | 'bottom-left', subscribedText, unsubscribedText }
logLevelwarnsilent | error | warn | info | debug
languagenavigator.languageLanguage of slidedown/bell texts and device.locale

API

await Pushizo.setConsentGiven(true);
await Pushizo.login('user_42', identityHash?);        // anonymous → identified
await Pushizo.login('user_42', undefined, { email: 'ali@example.com', sms: '+905321234567', tags: { plan: 'pro' }, aliases: { crm_id: '42' } }); // login with a profile: validated first, applied in one call after login
await Pushizo.logout();

Pushizo.User.addTag('plan', 'pro');   Pushizo.User.addTags({ a: '1' });
Pushizo.User.removeTag('plan');       Pushizo.User.removeTags(['a', 'b']);
Pushizo.User.getTags();               Pushizo.User.setLanguage('tr');
Pushizo.User.setProperty('city', 'İzmir');
Pushizo.User.addAlias('crm_id', '…'); Pushizo.User.addAliases({ crm_id: '…' }); Pushizo.User.removeAlias('crm_id');
Pushizo.User.id; Pushizo.User.externalId;

await Pushizo.User.pushSubscription.optIn();   // asks for permission if needed
await Pushizo.User.pushSubscription.optOut();
Pushizo.User.pushSubscription.id / optedIn / state;      // state: { id, token, optedIn, permission }
const off = Pushizo.User.pushSubscription.addObserver((state) => …); // off() removes the listener
Pushizo.User.pushSubscription.removeObserver(observer); // equivalent to off()

Pushizo.Notifications.permission;               // 'default' | 'granted' | 'denied' | 'unsupported'
await Pushizo.Notifications.requestPermission(); // permission + subscription → boolean
Pushizo.Notifications.addClickListener(({ notification, result }) => …); // result.url, result.actionId
Pushizo.Notifications.addForegroundLifecycleListener((e) => e.preventDefault()); // don't show while the page is open
Pushizo.Notifications.addForegroundLifecycleListener((e) => { e.preventDefault(); later(() => e.display()); }); // defer, then show
Pushizo.Notifications.addPermissionObserver(({ permission, state }) => …); // permission: boolean, state: 'granted' | …
Pushizo.Notifications.removePermissionObserver(observer);
await Pushizo.Notifications.clearAll();         // closes displayed notifications
Pushizo.Notifications.removeClickListener(listener); Pushizo.Notifications.removeForegroundLifecycleListener(listener);
await Pushizo.Notifications.setBadgeCount(3);   // app icon badge (App Badging API; installed PWA) → boolean, false when unsupported
await Pushizo.Notifications.clearBadge();

Pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9);
Pushizo.Debug.setLogLevel('debug');

const stopFlags = Pushizo.FeatureFlags.addObserver(() => render()); Pushizo.FeatureFlags.removeObserver(listener);
await Pushizo.Chat.getConfig();          // chat settings + online status (getConfig(true) skips the cache)
await Pushizo.Chat.getConversation();    // the conversation or null; also updates the unread count
Pushizo.Chat.setTyping(true);            // tells the agent the visitor is typing
Pushizo.Chat.attachmentUrl(attachmentId, true); // attachment download URL
Pushizo.Location.permissionGranted;      // browser location permission (last known state; never prompts)
Pushizo.pendingOperations;                      // number of queued operations

Tag/property/alias/event calls return synchronously and are written to the offline queue (localStorage, hs:<appId>); consecutive tag operations are merged. While no user exists yet, these operations wait in order and do not block operations that create the user, such as addEmail/addSms. While requiresPrivacyConsent is on, no network requests are made until consent is given; queued operations wait and are sent after setConsentGiven(true). Events stay in the queue until a subscription or login is available; they are sent with token_hash (a digest of the subscription token) and identity_hash if present. Sessions: session_start when the page becomes visible, session_end on pagehide (keepalive fetch).

Prompts: slidedown, bell, custom link

await Pushizo.init({
  appId: 'app_…',
  slidedown: { enabled: true, delaySeconds: 5, pageViews: 2 },
  bell: { enabled: true, position: 'bottom-right' },
  promptOptions: {
    backoffDays: [3, 7, 30],                 // [] → backoff disabled
    customlink: {
      enabled: true, style: 'button', size: 'medium',
      color: { button: '#e54b4d', text: '#ffffff' },
      text: { subscribe: 'Subscribe to notifications', unsubscribe: 'Unsubscribe', explanation: 'Be the first to hear about our campaigns.' },
      unsubscribeEnabled: true,
    },
  },
});
await Pushizo.Slidedown.promptPush();               // respects the schedule and triggers
await Pushizo.Slidedown.promptPush({ force: true }); // skips the schedule (if permission hasn't been asked)
Pushizo.CustomLink.render();                         // for a `.pushizo-customlink-container` added later
  • Prompts configured in the dashboard (GET /sdk/v1/apps/{appId}/config → web.prompt) are merged with the init options; init values take precedence.
  • When the slidedown is closed with "Not now", the rejection count increases and the prompt is hidden for 3 days after the 1st rejection, 7 days after the 2nd and 30 days after subsequent ones (slidedown.retryDays takes precedence as a fixed wait). Calling Notifications.requestPermission() directly is not affected by the schedule.
  • The welcome notification is shown locally when the subscription is first created on the server; it does not create a delivery record.
  • Action buttons (web_buttons, at most 2) and require_interaction are supported; clicking a button opens its url and adds button_id to the opened record.

Email and SMS subscriptions

Pushizo.User.addEmail('Ayse.Kaya@Pushizo.com');   // → ayse.kaya@pushizo.com
Pushizo.User.addSms('0090 (532) 123-45-67');       // → +905321234567 (E.164)
Pushizo.User.removeEmail('ayse.kaya@pushizo.com');
Pushizo.User.removeSms('+905321234567');

An invalid value throws ContactValidationError (error.channel: email | sms). The record is written to the queue and sent with POST /sdk/v1/apps/{appId}/subscriptions; if you are logged in, external_id (+ identity_hash) is added, otherwise the device's existing subscription is added as user.subscription_id, and the address is linked to the same user. Only the SHA-256 digest of the address and the subscription ID are stored on the device. For a visitor without a push subscription, the user identity (for tags, inbox and in-app) comes from the email/SMS subscription.

Email/SMS collection prompt: slidedown.collect: 'email' | 'sms' | 'email_sms', or Pushizo.Slidedown.promptEmail(), promptSms({ force: true }), promptEmailAndSms(). On acceptance the addresses are added with User.addEmail/addSms; the prompt is not shown again.

User preferences (categories)

const { preferences, categories } = await Pushizo.User.getPreferences();
// preferences[i] → { category, channel: null | 'web_push' | 'email' | 'sms' | …, optedIn, explicit, source, updatedAt }
// categories[i]  → { key, name: { tr, en }, description, channels: string[] | null, defaultOptedIn }
Pushizo.User.setPreferences([
  { category: 'promo', optedIn: false },                   // all channels
  { category: 'news', optedIn: true, channel: 'email' },   // email only
]);
Pushizo.User.getCategories(); // categories from config (no network call)

A subscription (push, or email/SMS if there is none) and proof of ownership are required; without a subscription getPreferences() throws a descriptive error. Records with explicit: false are derived from the category default.

In-app messages

Pushizo.InAppMessages.addTrigger('level', 5);           // trigger conditions (eq|neq|exists|gt|lt)
Pushizo.InAppMessages.addTriggers({ plan: 'pro', vip: true });
Pushizo.InAppMessages.removeTrigger('vip');  Pushizo.InAppMessages.clearTriggers();  Pushizo.InAppMessages.getTriggers();
Pushizo.InAppMessages.setScreen('pricing');             // screen conditions (call on SPA route changes)
Pushizo.Session.sendEvent('cart_viewed');               // event conditions

const off = Pushizo.InAppMessages.addClickListener(({ message, result }) => { /* message.id, result.actionId, result.url */ });
Pushizo.InAppMessages.addLifecycleListener({ willDisplay: ({ message }) => …, didDisplay: …, willDismiss: …, didDismiss: … });
Pushizo.InAppMessages.paused = true;  // don't show new messages (e.g. during checkout)
Pushizo.InAppMessages.setRenderer({     // custom rendering (null → default); HTML messages always use the default renderer
  show: (message, handle) => { const el = draw(message, { onButton: (id) => handle.buttonClicked(id), onClose: () => handle.dismissed() }); return { close: () => el.remove() }; }, // false → the message is skipped
});
  • The list is refreshed at session start and at most every 5 minutes with GET /sdk/v1/apps/{appId}/in-app?subscription_id=; without a subscription (push or email/SMS), in-app does not work.
  • Trigger groups are combined with OR, conditions within a group with AND; types are session_start, event, screen, trigger, session_duration. Frequency limits (remaining_impressions, min_interval_seconds, stop_after_interaction, app-wide in_app.min_interval_seconds) are also enforced locally; only one message is shown at a time, the one with the highest priority.
  • Rendering: an open Shadow DOM in the #hs-in-app element; layouts modal, banner_top, banner_bottom, fullscreen; accessible (role="dialog", focus management, Esc). Actions: dismiss, url (new tab), deeplink, tags, push_prompt, outcome.
  • Custom rendering (setRenderer): your site draws the message; triggers, frequency, event logging and button actions stay in the SDK. show returns { close }; handle.buttonClicked(id) and handle.dismissed() report the interaction. HTML messages are always shown by the default renderer.
  • Events impression, click (+button_id), dismiss → POST /sdk/v1/apps/{appId}/in-app/{messageId}/events (with variant_id for A/B variants).

Notification inbox

const page = await Pushizo.Inbox.list({ limit: 20 });     // newest first
// page.items[i] → { id, messageId, title, body, url, imageUrl, data, read, readAt, archivedAt, expiresAt, createdAt }
// page.unreadCount, page.nextCursor, page.hasMore
const next = await Pushizo.Inbox.list({ cursor: page.nextCursor! });
await Pushizo.Inbox.markRead(item.id);       // returns the updated item
await Pushizo.Inbox.markAllRead();           // { updated, unreadCount }
await Pushizo.Inbox.archive(item.id);        // removes it from the inbox
await Pushizo.Inbox.unreadCount();
const stop = Pushizo.Inbox.addObserver(({ type, itemId, unreadCount }) => updateBadge(unreadCount));

A user and a subscription belonging to them are required; the hash passed with login(externalId, identityHash) is added to requests.

Content cards

const feed = await Pushizo.ContentCards.list(20);   // { cards, unviewedCount }
await Pushizo.ContentCards.logImpression(feed.cards[0].id);
await Pushizo.ContentCards.logClick(id);            // click (also counts as an impression)
await Pushizo.ContentCards.dismiss(id);             // removes it from the feed
const view = await Pushizo.ContentCards.render('#cards', { limit: 20, theme: 'auto', color: '#2563eb', onCardClick: (card) => false, onFeedLoaded: (feed) => badge(feed.unviewedCount) });
await view.refresh();  view.destroy();                  // ready-made view (separate bundle, lazy loaded)

ContentCards.render(target, options) draws the ready-made card feed: it is a separate bundle (PushizoContentCards.js, gzip ≈ 3 KB; with a bundler use import { mountContentCards } from '@pushizo/web/content-cards' and { mount: mountContentCards }) and adds nothing to the main bundle. Open Shadow DOM, light/dark theme, right-to-left languages and text in 22 languages; loading, empty and error (retry) states; an impression is logged once at least half of a card is visible and a click on click (if onCardClick returns true your site opens the link), × dismisses the card. To draw the cards yourself, list + log* is enough. Cards do not appear in the notification inbox; the feed is ordered pinned → priority → newest. limit is 1-100 (default 50). Log an impression when a card is shown and a click when it is tapped; the stats appear on the campaign detail page.

Web personalization

Experiences created with Web Personalization in the dashboard change elements on your site (CSS selector) for visitors who match the condition and the target audience: text, image, link, hide/show. No code is needed; the SDK fetches the list (60 s cache), applies it and measures exposure and the conversion goal (SDK event, page, click). In A/B tests, the variant without changes is the control group. No HTML is written (only textContent and attributes); URLs can only be http(s):// or /path. Requires the Growth+ plan. To turn it off, use Pushizo.init({ ..., webPersonalization: false }).

The latest list is stored in the browser and applied on subsequent pages without waiting for the network. To keep the original content from briefly showing on the first visit, use the anti-flicker snippet:

<!-- In <head>, before the SDK: hides the page for at most 1.5 s on the first visit; removed once the SDK applies changes -->
<style>.pushizo-af body{opacity:0!important}</style>
<script>document.documentElement.classList.add('pushizo-af');
setTimeout(function(){document.documentElement.classList.remove('pushizo-af')},1500);</script>

An event goal is satisfied by SDK events such as Pushizo.Session.sendEvent('purchase'). The visual selector in the dashboard ("Pick on site") opens your site with the ?pushizo_editor=… parameter; the selection is sent only to the dashboard origin (page text is not sent).

Site search

While Site search is on in the dashboard, visitors search the indexed content of your site; if AI answers are on, they get a short answer with sources when they ask a question (guide). The search window is a separate bundle (PushizoSearch.js, about 5 KB gzip) loaded on the first open() call; the main bundle does not grow.

Pushizo.Search.attach('#site-search-button', { hotkey: true });   // opens on click and with Ctrl/⌘+K
await Pushizo.Search.open({ query: 'shipping', answers: true });    // open directly
Pushizo.Search.close();

// Headless: your own UI
const res = await Pushizo.Search.query('how much is shipping', { mode: 'answer', limit: 5 });
await Pushizo.Search.trackClick(res.query_id, res.results[0].url, 1);
OptionDescription
answersThe "Ask AI" option. If omitted, it follows the dashboard setting.
placeholder, color, themeInput text, accent color (#rrggbb), light / dark / auto.
hotkeyToggle with Ctrl/⌘+K.
newTabResults open in a new tab.
onSelect(result)Called when a result is chosen; return false to stop the SDK from navigating (single-page apps).
mountPass the bundle with import { mountSearchWidget } from '@pushizo/web/search-widget' instead of a script tag.
widgetUrl, nonce, containerBundle URL, CSP nonce and the element the window is appended to.

Typing only searches (mode: 'search'); the AI answer is requested with Enter or the "ask" button, and if it cannot be given the results are shown as usual. The window is keyboard accessible (arrow keys, Enter, Esc) and supports right-to-left languages and 22 languages. The search endpoint sends no subscription or visitor identity.

Size and testing

Budgets live in sdk/web/size-budget.json (gzip): CDN bundle ≈ 41.6 KB (budget 42 KB), service worker ≈ 4.3 KB (budget 6 KB), content card view ≈ 2.7 KB (budget 4 KB). The service worker stores received/opened feedback that could not be sent in IndexedDB and retries on the next push/click; on click it only opens http(s) URLs or URLs relative to the same origin. Unit tests are in sdk/web/src/__tests__ (Vitest + happy-dom), E2E in tests/e2e/web-sdk.spec.ts (Playwright). Manual verification: examples/web-vanilla (node examples/web-vanilla/serve.mjs, http://localhost:5173), examples/web-nextjs (npm run dev --workspace @pushizo/example-web-nextjs, http://localhost:3200).

Troubleshooting

SymptomCause / fix
permission: unsupportedHTTP origin (other than localhost), old Safari, private mode, or a site not added to the home screen on iOS. Use HTTPS.
SW registration 404PushizoSDKWorker.js is not at the site root or serviceWorkerPath is wrong.
No subscription is createdDashboard → Channels → Web Push is not enabled (vapid_public_key should come from GET /sdk/v1/apps/{appId}/config).
Notifications don't arriveCheck the provider response in Message Tracking: 410 subscription revoked; 401/403 VAPID key changed → refresh the browser subscription.
login 403Identity verification is enforced; get an identity_hash from your server.
In-app doesn't showNo subscription, trigger not satisfied, frequency limit reached, or paused; check the logs with logLevel: 'debug'.

On this page