Skip to main content

Introduction

When you have successfully set up HAPI Elements, window.hapi that contains the Javascript API will become available.

Listening to load event of HAPI Elements Script

To know when HAPI Elements loads, you can add an event listener:

window.addEventListener("hapi:load:script", () => {
// script has loaded
// you have access to window.hapi
})

An alternative way to know when HAPI Elements loads is to use await window.hapiInjector.inject() as follows:

const onLoadHapiElementsInjector = async (clientToken: string) => {
try {
window.hapiInjector.setConfig("clientToken", clientToken)
// Inject is a Promise that resolves when HAPI Elements script has successfully loaded
await window.hapiInjector.inject()
// You can now start using HAPI Elements Javascript API
console.log('[HAPI] Elements has loaded', window.hapi)
} catch (error) {
console.error(error)
}
}
info

Please note that the above event only runs once. As best practice, it is recommended that you show a loading spinner in areas where you have included Elements Widgets until HAPI Elements loads and takes over the loading of the element.


As part of this best practice, it is recommended to place hapi:load:script event listener high up in the component hierarchy and then store the load state in a variable like hasElementsLoaded: boolean and in files where you want to use the Elements JS API, you can do the following:

if (hasElementsLoaded) {
// have access to window.hapi
}

Namespaces (Submodules)

window.hapi contains some namespaced submodules as part of the Javascript API. These modules and their submodules are listed below:


Using TypeScript types package for window.hapi object

To bring type safety to the window.hapi, you would need to do the following:

import {
WindowHapi,
// WindowHapiSDKSubmodule
} from "@vonq/hapi-elements-types"

const isBrowser = typeof window !== "undefined" // SSR check

// we recommend that you don't use `window` directly but this exported variable throughout your app
// as `windowWithHapi.hapi.campaign.state.campaignForm.value`
export const windowWithHapi = isBrowser ? (window as unknown as WindowHapi & Window) : undefined
// or a shortcut
// as `hapiElementsSDK.campaign.state.campaignForm.value`
export const hapiElementsSDK = isBrowser ? windowWithHapi.hapi : undefined

// we don't recommend doing the following as `.hapi` property is not available until HAPI Elements is loaded thus will lead to false positives
/*
declare global {
interface Window { hapi: WindowHapiSDKSubmodule }
}
*/

For detailed list of available submodules, check the Playground.