HTML / Vanilla JS Integration
Standard integration without a framework, directly in HTML
data-ekooReqdata-ekoo-product-idReqdata-ekoo-localeautodata-ekoo-variantdata-ekoo-review-iddata-ekoo-on-eventdata-ekoo-directionnormaldata-ekoo-scale1data-ekoo-animationpulsedata-ekoo-animation-durationcontinuousdata-ekoo-always-openfalsedata-ekoo-show-imagetruedata-ekoo-not-fully-clickablefalsedata-ekoo-autoplayfalsedata-ekoo-audio-preloadmetadatadata-ekoo-show-transcriptfalsedata-ekoo-show-speed-buttonfalsedata-ekoo-closed-state-main-textdata-ekoo-closed-state-secondary-textdata-ekoo-modeautodata-shadow-modeopenwindow.EKOO_FORCE_SPA = truewindow.ekooShadowMode = "open"A static site does not necessarily have a server. A script run after your build writes the transcript and its JSON-LD into the generated HTML files. Crawlers read them without running JavaScript, and the widget stays interactive.
Before you start
Requirements
- Node.js 22.18 or later, which runs TypeScript without a compile step.
- A build step that writes your HTML pages into a folder (
dist,public,_site…).
Three values to prepare
- Website ID: in the backoffice, Settings → Organization, Organization ID field, or in the
data-ekooattribute of the widget already installed. - Product reference: exactly the one in
data-ekoo-product-idon your site and in Ekoo (ID or SKU), without changing convention. - Language: an explicit value such as
froren, the same asdata-ekoo-locale. Neverauto.
Is an A/B experiment comparing the widget with no widget running on these pages? Read the server rendering limits first.
1. Your starting HTML
Each product page already holds the Ekoo container and the widget script. The product reference and the language must be written as is: the script cannot read a value computed in JavaScript.
1<!-- Your product page before the build: product reference and language written as is in the HTML. -->2<div data-ekoo="YOUR_WEBSITE_ID" data-ekoo-product-id="SKU-1234" data-ekoo-locale="en"></div>34<script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js" defer></script>2. Add the prerender script
Copy these three files as is. The script uses parse5 to read the HTML without touching scripts, comments and templates.
1// Ekoo API response types23export type EkooReviewType = 'review' | 'testimony'45export interface EkooReviewUser {6 id: string7 firstname: string8 lastname: string9 image_url: string10 description: string11}1213export interface EkooReview {14 id: string15 type: EkooReviewType16 label: string17 rating: number18 audio_url: string19 is_active: boolean20 is_default: boolean21 transcript: string22 locale?: string23 created_at?: string24 user: EkooReviewUser25}2627export interface EkooExperimentVariation {28 id: string29 name: string30 widgetEnabled: boolean31 widgetConfigId: string | null32 audioSelection: string33 audioId: string | null34 audioPosition: number | null35 audioIdsByLocale?: Record<string, string>36 allocation: number37 position: number38 config?: unknown39}4041export interface EkooExperiment {42 id: string43 name: string44 variations: EkooExperimentVariation[]45}4647export interface EkooProduct {48 id: string49 external_id: string50 name?: string51 seo_name?: string52 seo_description?: string53 audio_url?: string54 website: { id: string; name?: string }55 features?: { ctaAnalytics: boolean }56 config?: Record<string, unknown>57 experiment?: EkooExperiment58 reviews: EkooReview[]59}6061export interface EkooProductList {62 limit: number63 offset: number64 count_item: number65 items: EkooProduct[]66}1// lib/ekoo.ts2import type { EkooProduct, EkooReview } from './ekoo-types'34const EKOO_ORIGIN = 'https://app.ekoo.co'56const AUDIO_FORMATS = new Map([7 ['mp3', 'audio/mpeg'],8 ['m4a', 'audio/mp4'],9 ['ogg', 'audio/ogg'],10 ['wav', 'audio/wav']11])1213export type EkooProductQuery = {14 websiteId: string15 productRef: string16 /** Same value as data-ekoo-locale. Never 'auto': the server does not know the browser language. */17 locale: string18}1920export type FetchEkooProductOptions = EkooProductQuery & {21 timeoutMs?: number22 init?: RequestInit23}2425export function buildEkooProductUrl({ websiteId, productRef, locale }: EkooProductQuery) {26 return `${EKOO_ORIGIN}/ws/websites/${encodeURIComponent(websiteId)}/products/${encodeURIComponent(productRef)}?${new URLSearchParams({ locale })}`27}2829/** Keeps a valid product only, or returns null. */30export function parseEkooProduct(body: unknown): EkooProduct | null {31 // An unknown product answers 200 with { type, message }: test the body, not the status.32 if (!body || typeof body !== 'object' || 'type' in body) return null33 if (!Array.isArray((body as EkooProduct).reviews)) return null34 return body as EkooProduct35}3637/** Returns the product, or null when Ekoo has nothing to render (unknown product, error, timeout). */38export async function fetchEkooProduct({39 websiteId,40 productRef,41 locale,42 timeoutMs = 1500,43 init44}: FetchEkooProductOptions): Promise<EkooProduct | null> {45 try {46 const res = await fetch(buildEkooProductUrl({ websiteId, productRef, locale }), {47 ...init,48 headers: { Accept: 'application/json' },49 signal: AbortSignal.timeout(timeoutMs)50 })51 if (!res.ok) return null52 return parseEkooProduct(await res.json())53 } catch {54 // Timeout or network error: the page renders without the Ekoo block.55 return null56 }57}5859/** Same choice as the widget: unknown explicit ID → first playable audio; no ID → default audio, then first playable. */60export function selectEkooReview(product: EkooProduct, reviewId?: string): EkooReview | null {61 const playable = product.reviews.filter((review) => review.audio_url && review.is_active)62 if (reviewId) return playable.find((review) => review.id === reviewId) ?? playable[0] ?? null63 return playable.find((review) => review.is_default) ?? playable[0] ?? null64}6566// created_at is a PostgreSQL timestamp ("2026-09-04 15:56:31.998283+00"), not ISO 8601.67function toIsoDate(value?: string) {68 const match = value69 ?.trim()70 .match(/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}(?::?\d{2})?)$/i)71 if (!match) return undefined7273 const [, day, time, fraction = '', zone] = match74 const offset = /^[+-]\d{2}$/.test(zone) ? `${zone}:00` : zone75 const date = new Date(`${day}T${time}.${fraction.slice(0, 3).padEnd(3, '0')}${offset}`)76 return Number.isNaN(date.getTime()) ? undefined : date.toISOString()77}7879/** AudioObject JSON-LD: data-ekoo-audio-id tells the widget not to add a second one. */80export function buildEkooAudioJsonLd(81 product: EkooProduct,82 review: EkooReview,83 { productJsonLdId }: { productJsonLdId?: string } = {}84) {85 const contentUrl = new URL(review.audio_url, EKOO_ORIGIN).href86 const extension = new URL(contentUrl).pathname.split('.').pop()?.toLowerCase() ?? ''87 const author = [review.user.firstname, review.user.lastname].filter(Boolean).join(' ')8889 return {90 '@context': 'https://schema.org',91 '@type': 'AudioObject',92 name: product.seo_name || product.name || undefined,93 description: product.seo_description || undefined,94 contentUrl,95 encodingFormat: AUDIO_FORMATS.get(extension),96 inLanguage: review.locale || undefined,97 transcript: review.transcript.replace(/\r\n?/g, '\n'),98 uploadDate: toIsoDate(review.created_at),99 about: productJsonLdId ? { '@id': productJsonLdId } : undefined,100 author: author ? { '@type': 'Person', name: author } : undefined101 }102}103104/** JSON.stringify does not escape "<": a transcript containing "</script>" would close the tag. */105export function serializeJsonLd(data: object) {106 return JSON.stringify(data).replace(/</g, '\\u003c')107}108109/** Escapes text for HTML, as content or as an attribute value. */110export function escapeHtml(text: string) {111 return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)112}113114/** Complete JSON-LD <script> tag, for templates that insert raw HTML. */115export function buildEkooJsonLdScriptTag(116 product: EkooProduct,117 review: EkooReview,118 options: { productJsonLdId?: string } = {}119) {120 const data = serializeJsonLd(buildEkooAudioJsonLd(product, review, options))121 return `<script type="application/ld+json" data-ekoo-seo="server" data-ekoo-audio-id="${escapeHtml(review.id)}">${data}</script>`122}1// scripts/ekoo-prerender.ts2// After your build: node scripts/ekoo-prerender.ts dist (Node.js 22.18 or later).3import { readdir, readFile, writeFile } from 'node:fs/promises'4import { join } from 'node:path'5import { parse, type DefaultTreeAdapterMap } from 'parse5'67import { buildEkooJsonLdScriptTag, escapeHtml, fetchEkooProduct, selectEkooReview } from '../lib/ekoo.ts'89const SUMMARY = 'Read the transcript'1011// The markers let you run the script again without duplicating the block.12const START = '<!-- ekoo:ssr:start -->'13const END = '<!-- ekoo:ssr:end -->'1415function* nodes(node: DefaultTreeAdapterMap['node']): Generator<DefaultTreeAdapterMap['node']> {16 yield node17 if ('childNodes' in node) {18 for (const child of node.childNodes) yield* nodes(child)19 }20}2122function removePreviousBlocks(html: string) {23 const comments = [...nodes(parse(html, { sourceCodeLocationInfo: true }))]24 .filter((node) => node.nodeName === '#comment' && node.sourceCodeLocation)25 .sort((a, b) => a.sourceCodeLocation!.startOffset - b.sourceCodeLocation!.startOffset)26 let output = ''27 let cursor = 028 let start: number | undefined29 for (const comment of comments) {30 const location = comment.sourceCodeLocation!31 const marker = html.slice(location.startOffset, location.endOffset)32 if (marker === START && start === undefined) start = location.startOffset33 if (marker === END && start !== undefined) {34 output += html.slice(cursor, start)35 cursor = location.endOffset36 start = undefined37 }38 }39 return output + html.slice(cursor)40}4142const blocks = new Map<string, Promise<string>>()4344function renderBlock(attributes: Record<string, string>, file: string) {45 const websiteId = attributes['data-ekoo'] ?? ''46 const productRef = attributes['data-ekoo-product-id'] ?? ''47 const locale = attributes['data-ekoo-locale'] ?? ''48 const reviewId = attributes['data-ekoo-review-id'] ?? ''4950 if (!websiteId || !productRef || !locale || locale === 'auto') {51 console.warn(`${file}: ${productRef} (missing or "auto" locale: cannot be resolved at build time)`)52 return Promise.resolve('')53 }5455 const key = [websiteId, productRef, locale, reviewId].join('|')56 if (!blocks.has(key)) {57 blocks.set(58 key,59 (async () => {60 const product = await fetchEkooProduct({ websiteId, productRef, locale, timeoutMs: 10_000 })61 const review = product ? selectEkooReview(product, reviewId || undefined) : null62 if (!product || !review?.transcript.trim()) return ''6364 const transcript = `<section class="ekoo-transcript"><details><summary>${SUMMARY}</summary><p style="white-space: pre-line">${escapeHtml(review.transcript)}</p></details></section>`65 return START + buildEkooJsonLdScriptTag(product, review) + transcript + END66 })()67 )68 }69 return blocks.get(key)!70}7172async function prerender(file: string) {73 const original = await readFile(file, 'utf8')74 const html = removePreviousBlocks(original)75 const placeholders = [...nodes(parse(html, { sourceCodeLocationInfo: true }))]76 .filter((node): node is DefaultTreeAdapterMap['element'] =>77 'tagName' in node && !!node.sourceCodeLocation &&78 node.attrs.some((attribute) => attribute.name === 'data-ekoo-product-id')79 )80 .sort((a, b) => a.sourceCodeLocation!.startOffset - b.sourceCodeLocation!.startOffset)8182 let output = ''83 let last = 084 for (const node of placeholders) {85 const start = node.sourceCodeLocation!.startOffset86 const attributes = Object.fromEntries(node.attrs.map(({ name, value }) => [name, value]))87 output += html.slice(last, start) + (await renderBlock(attributes, file))88 last = start89 }90 output += html.slice(last)9192 if (output !== original) await writeFile(file, output)93}9495const root = process.argv[2] ?? 'dist'96for (const entry of await readdir(root, { recursive: true })) {97 if (entry.endsWith('.html')) await prerender(join(root, entry))98}3. Run it after your build
Keep your build command and add the script after it, then add parse5 and run npm install. Replace dist with the folder your build writes the HTML pages to.
1{2 "scripts": {3 "build": "your-current-build-command && node scripts/ekoo-prerender.ts dist"4 },5 "devDependencies": {6 "parse5": "8.0.0"7 }8}4. What the script adds
In front of each Ekoo container, and only there, the script adds the JSON-LD and the transcript between two markers. The rest of the file does not change, and running it again replaces the block instead of duplicating it.
1<!-- AudioObject JSON-LD: data-ekoo-audio-id tells the widget not to add a second one. -->2<script type="application/ld+json" data-ekoo-seo="server" data-ekoo-audio-id="AUDIO_ID">3 {"@context":"https://schema.org","@type":"AudioObject", "...": "..."}4</script>56<!-- Transcript: text escaped by the framework, next to the widget and never inside it. -->7<section class="ekoo-transcript">8 <details>9 <summary>Read the transcript</summary>10 <p>…</p>11 </details>12</section>1314<!-- The widget stays client-side: it becomes interactive once its script loads. -->15<div data-ekoo="YOUR_WEBSITE_ID" data-ekoo-product-id="PRODUCT_REF" data-ekoo-locale="en"></div>1617<script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js" defer></script>Content fixed until the next build
The transcript written into your files only changes at the next build: an audio unpublished in Ekoo stays visible until then. Rebuild regularly, for instance every day, and after each unpublication. If Ekoo does not answer during the build, the block is removed until the next build. Slots created in JavaScript (window.ekooOptions), product references computed by a function and the auto locale are not handled: those pages keep the widget alone.
Check
- Transcript in the source code: open a generated HTML file, look for
data-ekoo-audio-idand a sentence of the transcript. - Playback: the player shows up and the audio starts on click.
- Product change: open another product page; the transcript and the audio must match that product.
Detailed checks, including no duplicate JSON-LD: SSR, SEO & GEO guide.
Without a build step, simply add the widget as below. The transcript is then only readable once JavaScript has run.
Recommended method: data attributes
Add a container with data-ekoo-* attributes and load the official script. The widget initializes automatically.
1<!-- Widget container -->2<ekoo-widget3 data-ekoo="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"4 data-ekoo-product-id="my-product-123"5 data-ekoo-locale="fr"6></ekoo-widget>78<!-- Ekoo script — load once per page -->9<script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js"></script>Dynamic Product ID
If the product identifier is dynamic (e.g. extracted from the URL or a page attribute), you can use a JavaScript function to retrieve it and inject it into the data-ekoo-product-id attribute.
1<!-- Container — the ID will be injected by the script below -->2<div id="ekoo-container"3 data-ekoo="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"4 data-ekoo-locale="fr"5></div>67<script>8 // Retrieve the product ID from the URL, e.g.: /products/my-product-1239 function getProductId() {10 const parts = window.location.pathname.split('/');11 return parts[parts.length - 1];12 }1314 const container = document.getElementById('ekoo-container');15 if (container) {16 container.setAttribute('data-ekoo-product-id', getProductId());17 }18</script>1920<!-- Ekoo script — AFTER the product ID injection -->21<script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js"></script>Declare callbacks BEFORE the script
If you use data-ekoo-on-event to receive widget events, declare the callback function before loading the Ekoo script. Otherwise, the script will not find the function at initialization time.
1<script>2 // Declare the function BEFORE the Ekoo script3 // The callback receives a single argument: the full stats body object4 function onEkooEvent(data) {5 console.log('Ekoo event:', data.stats.type, data);6 // E.g.: send to Google Analytics, dataLayer, etc.7 }8</script>910<ekoo-widget11 data-ekoo="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"12 data-ekoo-on-event="onEkooEvent"13 data-ekoo-product-id="my-product-123"14 data-ekoo-locale="fr"15></ekoo-widget>1617<script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js"></script>Widget lifecycle
The widget emits ekoovisible once a review has been selected and is ready to display, and ekoohidden when it cannot display. Declare listeners before the widget script.
1<script>2 // Register listeners BEFORE loading the Ekoo widget script.3 document.addEventListener('ekoovisible', (event) => {4 const { productId, reviewId, review } = event.detail;5 console.log('Selected audio:', { productId, reviewId, review });6 });78 document.addEventListener('ekoohidden', ({ detail }) => {9 console.warn('Widget hidden:', detail.reason);10 });11</script>ekoovisible includes the widget, product and review identifiers, plus a public review object (audio and contributor). This contract is versioned and may gain fields without breaking integrations. ekoohidden exposes one of these reasons: noMatchingProduct, noAudios, experimentDisabled, or loadError.
Common pitfalls
- Script loaded before the container: if the
data-ekoocontainer is not yet in the DOM, the widget will not mount. Usedeferor place the script at the end of<body>. - Missing or incorrect Product ID: the widget will not display if the ID does not match any published audio.
- Multiple scripts loaded: only load the
widget-4.0.0-standalone.jsscript once per page, even if you have multiple containers. - Undeclared callback: the function referenced in
data-ekoo-on-eventmust be globally accessible (onwindow). - Wrong script URL: always use
widget-4.0.0-standalone.js, not an older version.