HTML / Vanilla JS Integration

Standard integration without a framework, directly in HTML

The widget auto-loads its config from the backoffice. Appearance attributes are optional overrides — no need to set them if the backoffice is configured.
Core attributes
data-ekooReq
string
Your Ekoo website UUID: backoffice, Settings → Organization, Organization ID field.
data-ekoo-product-idReq
string
Product reference (must match exactly what is in your Ekoo catalog).
data-ekoo-locale
string·default: auto
Locale code: fr, en, es, it, de, ar, cn, tw, hk, jp, kr, nl, tr, pl, pt, lu, be, ru. "auto" = navigator.language detection.
data-ekoo-variant
string
Stable reference of a widget configuration. The product, its audios, and its reviewers still come from data-ekoo-product-id; only the widget styling changes.
data-ekoo-review-id
string
ID of a specific audio review. If omitted: the product's default audio, otherwise the first published audio.
data-ekoo-on-event
string (fn name)
Name of a global window function called on each widget event (printed, played-0, played-25…).
Appearance — backoffice overrides
data-ekoo-direction
normal | reverse·default: normal
Expansion direction. normal = left-to-right, reverse = right-to-left.
data-ekoo-scale
number·default: 1
Scale factor (e.g. "1.2" for 20% larger).
data-ekoo-animation
string·default: pulse
Animation type for the widget icon at rest.
data-ekoo-animation-duration
string·default: continuous
Animation duration.
data-ekoo-always-open
boolean·default: false
If "true", the widget stays permanently expanded.
data-ekoo-show-image
boolean·default: true
Show or hide the product image in the widget.
data-ekoo-not-fully-clickable
boolean·default: false
If "true", only the play button is clickable.
data-ekoo-autoplay
boolean·default: false
Automatically start audio playback on load.
data-ekoo-audio-preload
metadata | none·default: metadata
Standalone 4.0.0: overrides the backoffice setting. “none” waits until the first click to load the file and disables autoplay.
data-ekoo-show-transcript
boolean·default: false
Show a button to read the audio transcript.
data-ekoo-show-speed-button
boolean·default: false
Show a playback speed control.
data-ekoo-closed-state-main-text
string
Main CTA text shown when the widget is collapsed.
data-ekoo-closed-state-secondary-text
string
Secondary text below the CTA when the widget is collapsed.
SPA & Shadow DOM
data-ekoo-mode
spa | static·default: auto
Forces rendering mode. Auto-detected (Next.js, Nuxt, React, Vue, Angular, Sapper). Only use if auto-detection fails.
data-shadow-mode
open | closed·default: open
"open" (default) enables inspection, external CSS access and analytics tracking. Set to "closed" to fully isolate the widget.
Global JS config
window.EKOO_FORCE_SPA = true
Forces SPA mode globally (alternative to data-ekoo-mode="spa" on each widget).
window.ekooShadowMode = "open"
Global Shadow DOM mode (alternative to data-shadow-mode on each widget).

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

  1. Website ID: in the backoffice, Settings → Organization, Organization ID field, or in the data-ekoo attribute of the widget already installed.
  2. Product reference: exactly the one in data-ekoo-product-id on your site and in Ekoo (ID or SKU), without changing convention.
  3. Language: an explicit value such as fr or en, the same as data-ekoo-locale. Never auto.

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.

Product page
html
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>
3
4<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.

lib/ekoo-types.ts
typescript
1// Ekoo API response types
2
3export type EkooReviewType = 'review' | 'testimony'
4
5export interface EkooReviewUser {
6 id: string
7 firstname: string
8 lastname: string
9 image_url: string
10 description: string
11}
12
13export interface EkooReview {
14 id: string
15 type: EkooReviewType
16 label: string
17 rating: number
18 audio_url: string
19 is_active: boolean
20 is_default: boolean
21 transcript: string
22 locale?: string
23 created_at?: string
24 user: EkooReviewUser
25}
26
27export interface EkooExperimentVariation {
28 id: string
29 name: string
30 widgetEnabled: boolean
31 widgetConfigId: string | null
32 audioSelection: string
33 audioId: string | null
34 audioPosition: number | null
35 audioIdsByLocale?: Record<string, string>
36 allocation: number
37 position: number
38 config?: unknown
39}
40
41export interface EkooExperiment {
42 id: string
43 name: string
44 variations: EkooExperimentVariation[]
45}
46
47export interface EkooProduct {
48 id: string
49 external_id: string
50 name?: string
51 seo_name?: string
52 seo_description?: string
53 audio_url?: string
54 website: { id: string; name?: string }
55 features?: { ctaAnalytics: boolean }
56 config?: Record<string, unknown>
57 experiment?: EkooExperiment
58 reviews: EkooReview[]
59}
60
61export interface EkooProductList {
62 limit: number
63 offset: number
64 count_item: number
65 items: EkooProduct[]
66}
lib/ekoo.ts
typescript
1// lib/ekoo.ts
2import type { EkooProduct, EkooReview } from './ekoo-types'
3
4const EKOO_ORIGIN = 'https://app.ekoo.co'
5
6const AUDIO_FORMATS = new Map([
7 ['mp3', 'audio/mpeg'],
8 ['m4a', 'audio/mp4'],
9 ['ogg', 'audio/ogg'],
10 ['wav', 'audio/wav']
11])
12
13export type EkooProductQuery = {
14 websiteId: string
15 productRef: string
16 /** Same value as data-ekoo-locale. Never 'auto': the server does not know the browser language. */
17 locale: string
18}
19
20export type FetchEkooProductOptions = EkooProductQuery & {
21 timeoutMs?: number
22 init?: RequestInit
23}
24
25export function buildEkooProductUrl({ websiteId, productRef, locale }: EkooProductQuery) {
26 return `${EKOO_ORIGIN}/ws/websites/${encodeURIComponent(websiteId)}/products/${encodeURIComponent(productRef)}?${new URLSearchParams({ locale })}`
27}
28
29/** 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 null
33 if (!Array.isArray((body as EkooProduct).reviews)) return null
34 return body as EkooProduct
35}
36
37/** 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 init
44}: 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 null
52 return parseEkooProduct(await res.json())
53 } catch {
54 // Timeout or network error: the page renders without the Ekoo block.
55 return null
56 }
57}
58
59/** 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] ?? null
63 return playable.find((review) => review.is_default) ?? playable[0] ?? null
64}
65
66// created_at is a PostgreSQL timestamp ("2026-09-04 15:56:31.998283+00"), not ISO 8601.
67function toIsoDate(value?: string) {
68 const match = value
69 ?.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 undefined
72
73 const [, day, time, fraction = '', zone] = match
74 const offset = /^[+-]\d{2}$/.test(zone) ? `${zone}:00` : zone
75 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}
78
79/** 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).href
86 const extension = new URL(contentUrl).pathname.split('.').pop()?.toLowerCase() ?? ''
87 const author = [review.user.firstname, review.user.lastname].filter(Boolean).join(' ')
88
89 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 } : undefined
101 }
102}
103
104/** 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}
108
109/** 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}
113
114/** 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}
scripts/ekoo-prerender.ts
typescript
1// scripts/ekoo-prerender.ts
2// 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'
6
7import { buildEkooJsonLdScriptTag, escapeHtml, fetchEkooProduct, selectEkooReview } from '../lib/ekoo.ts'
8
9const SUMMARY = 'Read the transcript'
10
11// The markers let you run the script again without duplicating the block.
12const START = '<!-- ekoo:ssr:start -->'
13const END = '<!-- ekoo:ssr:end -->'
14
15function* nodes(node: DefaultTreeAdapterMap['node']): Generator<DefaultTreeAdapterMap['node']> {
16 yield node
17 if ('childNodes' in node) {
18 for (const child of node.childNodes) yield* nodes(child)
19 }
20}
21
22function 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 = 0
28 let start: number | undefined
29 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.startOffset
33 if (marker === END && start !== undefined) {
34 output += html.slice(cursor, start)
35 cursor = location.endOffset
36 start = undefined
37 }
38 }
39 return output + html.slice(cursor)
40}
41
42const blocks = new Map<string, Promise<string>>()
43
44function 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'] ?? ''
49
50 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 }
54
55 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) : null
62 if (!product || !review?.transcript.trim()) return ''
63
64 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 + END
66 })()
67 )
68 }
69 return blocks.get(key)!
70}
71
72async 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)
81
82 let output = ''
83 let last = 0
84 for (const node of placeholders) {
85 const start = node.sourceCodeLocation!.startOffset
86 const attributes = Object.fromEntries(node.attrs.map(({ name, value }) => [name, value]))
87 output += html.slice(last, start) + (await renderBlock(attributes, file))
88 last = start
89 }
90 output += html.slice(last)
91
92 if (output !== original) await writeFile(file, output)
93}
94
95const 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.

package.json
json
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.

Generated HTML
html
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>
5
6<!-- 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>
13
14<!-- 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>
16
17<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

  1. Transcript in the source code: open a generated HTML file, look for data-ekoo-audio-id and a sentence of the transcript.
  2. Playback: the player shows up and the audio starts on click.
  3. 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.

Simple integration
html
1<!-- Widget container -->
2<ekoo-widget
3 data-ekoo="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
4 data-ekoo-product-id="my-product-123"
5 data-ekoo-locale="fr"
6></ekoo-widget>
7
8<!-- 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.

Dynamic Product ID from the URL
html
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>
6
7<script>
8 // Retrieve the product ID from the URL, e.g.: /products/my-product-123
9 function getProductId() {
10 const parts = window.location.pathname.split('/');
11 return parts[parts.length - 1];
12 }
13
14 const container = document.getElementById('ekoo-container');
15 if (container) {
16 container.setAttribute('data-ekoo-product-id', getProductId());
17 }
18</script>
19
20<!-- 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.

Event callback
html
1<script>
2 // Declare the function BEFORE the Ekoo script
3 // The callback receives a single argument: the full stats body object
4 function onEkooEvent(data) {
5 console.log('Ekoo event:', data.stats.type, data);
6 // E.g.: send to Google Analytics, dataLayer, etc.
7 }
8</script>
9
10<ekoo-widget
11 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>
16
17<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.

Listen to widget state
html
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 });
7
8 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-ekoo container is not yet in the DOM, the widget will not mount. Use defer or 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.js script once per page, even if you have multiple containers.
  • Undeclared callback: the function referenced in data-ekoo-on-event must be globally accessible (on window).
  • Wrong script URL: always use widget-4.0.0-standalone.js, not an older version.

Going further