Skip to content

addEventListener

The addEventListener method allows you to register event listeners for Htag events. This is useful for executing custom code when specific events occur during the ad lifecycle.

window.htag.api('1').addEventListener(eventName, handler, options);
  • eventName (string): The name of the event to listen for
  • handler (function): The function to call when the event occurs
  • options (object, optional): Configuration options for the listener
    • once (boolean): If true, the listener will be automatically removed after firing once (default: false)

The once option automatically removes the listener after it fires for the first time:

// This listener will only fire once
window.htag.api('1').addEventListener(
'ready',
() => {
console.log('One-time initialization');
},
{ once: true },
);
// Useful with promises for waiting
await new Promise((resolve) => {
window.htag.api('1').addEventListener('ready', resolve, { once: true });
});