Skip to content

SDK Integration ​

Adding the SDK ​

The TrueX Ad Renderer is published on npm as @truex/ad-renderer. For a web app built around a package.json, add the dependency:

sh
npm add @truex/ad-renderer@1.14.6 --save-exact

This adds an entry to the "dependencies" section of package.json, for example:

json
"dependencies": {
    "@truex/ad-renderer": "1.14.6"
}

Then build and run your web app as usual, for example with npm start for webpack-based projects.

Alternatively, load the library with a script tag:

html
<script src="https://cdn.jsdelivr.net/npm/@truex/ad-renderer@1.14.6"></script>

To always load the latest version:

html
<script src="https://cdn.jsdelivr.net/npm/@truex/ad-renderer@latest"></script>

Choosing the Renderer Class ​

The library has one renderer class for each device type, so that the correct ad tracking is used:

ClassUse for
TruexAdRendererCTVConnected TV apps, web-enabled smart TVs, and game consoles
TruexAdRendererDesktopDesktop browsers
TruexAdRendererMobileMobile browsers and mobile webviews

The deprecated TruexAdRenderer class maps to TruexAdRendererCTV. All three classes have the same methods and events, described on this page and on the Events page.

Quick Example ​

The renderer is created with the adParameters JSON from the VAST response - see Resolving adParameters. The example shows the CTV class; for desktop or mobile, use TruexAdRendererDesktop or TruexAdRendererMobile:

javascript
import { TruexAdRendererCTV, TruexAdEventType } from '@truex/ad-renderer';

videoController.pause();

let adFreePod = false;

const tar = new TruexAdRendererCTV(adParameters);
tar.subscribe(handleTruexAdEvent);

try {
  await tar.init();
  await tar.start();
} catch (err) {
  console.error('ad error: ' + err);
  tar.stop();
  resumePlayback();
}

function handleTruexAdEvent(event) {
  switch (event.type) {
    case TruexAdEventType.AD_FREE_POD:
      adFreePod = true; // the user did sufficient interaction for an ad credit
      break;

    case TruexAdEventType.AD_ERROR:
      console.error('ad error: ' + event.errorMessage);
      resumePlayback();
      break;

    case TruexAdEventType.NO_ADS_AVAILABLE:
    case TruexAdEventType.AD_COMPLETED:
      // The ad is not available, or has completed. Depending on the adFreePod flag, either the main
      // video or the ad fallback videos are resumed.
      resumePlayback();
      break;
  }
}

function resumePlayback() {
  if (adFreePod) {
    // The user has the credit, resume the main video after the ad break.
    videoController.skipAdBreak();
    videoController.resumeMainVideo();
  } else {
    // Continue with playing the remaining fallback ad videos in the ad break.
    videoController.skipCurrentAd();
    videoController.resumeAdBreak();
  }
}

TruexAdRenderer Methods ​

constructor ​

typescript
constructor(parameters: TruexAdRendererParameters, options?: TruexAdRendererOptions)

parameters is one of:

  • the adParameters object from the VAST response - the usual case, e.g. const tar = new TruexAdRendererCTV(adParameters), see Resolving adParameters
  • a VAST config URL string
  • an object with a vast_config_url field and an optional user_id

options are optional overrides:

OptionTypeDescription
showLoadingSpinnerbooleanIf true (default), a loading indicator is shown while the choice card display elements load, i.e. while waiting for image assets
userAdvertisingIdstringThe id used for user ad tracking. If omitted, the network_user_id in the VAST config URL is used, or else a random id
supportsUserCancelStreambooleanIf true, enables the userCancelStream event for back actions from the choice card. Defaults to false, which means back actions cause optOut or adCompleted events instead
useHistoryBackActionsbooleanOverrides the platform's auto-detected history API back handling. Omit it to keep the default. false handles the raw back key (LG apps with disableBackHistoryAPI: true). true waits for popstate
appIdstringThe application id or package name, for tracking
useIntegration{ name, version } or an array of themThe host integration name and version, for tracking. An array tracks multiple integrations
useWebMAFbooleanIf true and running on the PS4, all ad videos are played via the WebMAF API, to work around WebMAF load failures caused by creating HTML5 video elements
keyMapOverridesobjectKey codes for each input action, overriding the platform's built-in key mapping. Intended for platforms that TAR does not support yet

keyMapOverrides has the fields select, back, moveUp, moveDown, moveLeft, and moveRight, each a key code or an array of key codes:

javascript
{
    select: [32, 13], // space or enter
    back: [27, 8, 127], // esc or backspace or del
    moveUp: 38,
    moveDown: 40,
    moveLeft: 37,
    moveRight: 39
}

The renderer also has a read-only version field with the TAR build version.

init ​

javascript
/**
 * Queries for the vast config result
 *
 * @returns {Promise} resolves to the resulting the vast config result object
 */
function init()

This should be called by the host app code in order to initialize the TruexAdRenderer instance. The renderer will use the VAST config url passed to it in the constructor and make a request to the TrueX ad server to see what ads are available.

You may initialize TruexAdRenderer early (a few seconds before the next pod even starts) in order to give it extra time to make the ad request. The renderer will output an adFetchCompleted event at completion of this ad request. This event can be used to facilitate the implementation of a timeout or loading indicator, and when to make the call to start.

start ​

javascript
/**
 * Starts the choice card and engagement flow
 *
 * @param {Object} [vastConfig] optional defaults to the value obtained via the init() call.
 *
 * @param {HTMLElement} [parentElement] parent DOM element to add the ad overlay/choice card to.
 *      Defaults to document.documentElement.
 *
 * @return {Promise} promise that completes when the choice card loads, resolves to the div holding the ad overlay.
 */
function start(vastConfig, parentElement)

This should be called by the host app code when the app is ready to display the TrueX unit to the user. This can be called anytime after the renderer is initialized.

The host app should have as much extraneous UI hidden as possible, including player controls, status bars and soft buttons/keyboards. On constrained devices, especially connected TV devices, it is preferable to also unload the main video if possible, resuming it after the ad unit is completed.

After calling start, the host app code should wait for a terminal event before taking further actions, while keeping track of whether the adFreePod event has fired.

In a non-error flow, the renderer will first wait for the ad request triggered in init to finish if it has not already. It will then display the TrueX ad unit to the user in a new component (added to the TruexAdRenderer parent component) and then fire the adStarted event. adFreePod and other events may fire after this point, depending on the user's choices, followed by one of the terminal events.

stop ​

javascript
/**
 * Allow ads to be forcibly closed by the host app or test script.
 * (Needs to be possible if the app needs to reset, otherwise back actions can be permanently
 * blocked if the ad is not cleaned up.)
 */
function stop()

The stop method is only called when the host app needs the renderer to immediately stop and destroy all related resources. It is not needed after a terminal event, when the renderer has already finished - just remove the ad overlay and the references to the renderer.

Examples include:

  • the user backs out of the video stream to return to the normal app UI
  • there was an unrelated error that requires immediate halt of the current ad unit
  • a call to init or start failed
  • the app code has reached a custom timeout waiting for either the adFetchCompleted or adStarted events

The renderer instance should not be used again after calling stop -- please remove all references to it afterwards.

pause ​

javascript
/**
 * Pauses an ad if the hosting app needs to suspend/resume itself.
 * I.e. Any ad videos are paused and countdowns suspended.
 */
function pause()

resume ​

javascript
/**
 * Resumes a previously paused ad. I.e. any paused ad videos are resumed, as well as suspended countdowns.
 */
function resume()

subscribe ​

typescript
subscribe(callback: (event: TruexAdEvent) => unknown): void
subscribe(type: TruexAdEventName, callback: (event) => unknown): void

An ad event object has a type field that describes which event has occurred - one of the TruexAdEventType constants - along with other data fields depending on the event.

Use subscribe to listen to ad events emitted from the renderer. The key ones the host app should listen to are:

javascript
adFreePod
adCompleted
noAdsAvailable
adError

To listen to all ad events, just pass in a single callback as the argument, e.g. tar.subscribe(handleAdEvent).

To listen to a particular ad event, pass in the type to listen to and the callback, e.g. tar.subscribe('adCompleted', handleAdCompleted)

The ad event names are available as the TruexAdEventType constants exported by the package, e.g. TruexAdEventType.AD_FREE_POD. The renderer's adEvents field is deprecated.

unsubscribe ​

typescript
unsubscribe(callback: (event: TruexAdEvent) => unknown): void
unsubscribe(type: TruexAdEventName, callback: (event) => unknown): void

Removes a callback that was passed to subscribe, with the same arguments.

setAdVolume ​

typescript
setAdVolume(volume: number): void

Sets the choice card voiceover volume, from 0 to 100.

Integration documentation for Infillion Ads