From c797fcd2665120e6e9fd9ce5f198698c0d52afc8 Mon Sep 17 00:00:00 2001 From: Zino Hofmann Date: Wed, 17 Jan 2024 08:46:44 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20queue=20zaraz=20method=20ca?= =?UTF-8?q?lls=20until=20initialized?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/helpers/get-zaraz.ts | 52 +++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/src/helpers/get-zaraz.ts b/src/helpers/get-zaraz.ts index 7b7abe2..0d2cd61 100644 --- a/src/helpers/get-zaraz.ts +++ b/src/helpers/get-zaraz.ts @@ -1,12 +1,48 @@ -/** - * A utility that checks if zaraz exists on the window object. If not it throws - * an error. Else returns the zaraz object. - */ +type QueueItem = { + method: 'track' | 'set' | 'ecommerce'; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + arguments: any; +}; + +let queue: QueueItem[] = []; + export function getZaraz() { - if (typeof window !== 'undefined' && !window?.zaraz) { - throw new Error( - `Cannot use Zaraz Web API, because window.zaraz is not defined.`, - ); + if (typeof window === 'undefined') { + throw new Error(`Cannot use Zaraz Web API, because window is not defined.`); + } + + if (!window?.zaraz) { + // eslint-disable-next-line no-console + console.log(`Zaraz Web API is not initialized. Queueing events...`); + + return { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + track: (...args: any[]) => { + queue.push({ method: 'track', arguments: args }); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set: (...args: any[]) => { + queue.push({ method: 'set', arguments: args }); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ecommerce: (...args: any[]) => { + queue.push({ method: 'ecommerce', arguments: args }); + }, + }; + } + + if (queue.length > 0) { + // eslint-disable-next-line no-console + console.log(`Zaraz Web API is initialized. Flushing queue...`); + + queue.forEach((event) => { + window.zaraz[event.method](...event.arguments); + }); + + // eslint-disable-next-line no-console + console.log(`Zaraz Web API queue flushed.`); + + queue = []; // Clear the queue } return window.zaraz;