Skip to main content

Overview

This guide will walk you through creating a basic ad player that fetches a VAST tag and plays a video advertisement on Smart TV platforms.
Time to complete: ~5 minutesWhat you’ll build: A fully functional video ad player with autoplay, skip button, progress tracking, and event handling

Prerequisites

Before starting, ensure you have:
  • Node.js 14+ installed
  • A Smart TV project (or any JavaScript/TypeScript project)
  • A VAST tag URL for testing (you can use a test VAST from your ad server)

Step-by-Step Guide

1

Install the SDK

Install Adgent SDK using your preferred package manager:
npm install adgent-sdk
2

Create an HTML container

Add a container element where the ad player will render:
<div id="ad-container" style="width: 1920px; height: 1080px; position: relative;"></div>
The container must have a defined width and height. For Smart TVs, use 1920x1080 (Full HD) or 3840x2160 (4K) dimensions.
3

Initialize the SDK

Import and initialize the AdgentSDK with your VAST URL:
import { AdgentSDK } from 'adgent-sdk';

const sdk = new AdgentSDK({
  container: document.getElementById('ad-container')!,
  vastUrl: 'https://example.com/vast.xml',
  targetBitrate: 2500, // Prefer 1080p (2500 kbps)
  skipOffset: 5, // Allow skip after 5 seconds
  debug: true, // Enable console logging
  
  // Event callbacks
  onStart: () => {
    console.log('Ad started playing');
  },
  onComplete: () => {
    console.log('Ad completed - resume main content');
    // Resume your main video content here
  },
  onError: (error) => {
    console.error('Ad error:', error.message);
    // Gracefully handle error - resume main content
  },
  onSkip: () => {
    console.log('User skipped the ad');
  }
});
4

Initialize and play the ad

Call init() to fetch the VAST and prepare the player, then call play() to start playback:
async function playAd() {
  try {
    // Fetch VAST, select media file, create video element
    await sdk.init();
    
    // Ad will autoplay with muted audio (Nuclear Mute strategy)
    // No need to call play() - it's handled automatically
    
    console.log('Ad initialized and playing');
  } catch (error) {
    console.error('Failed to initialize ad:', error);
    // Handle error gracefully
  }
}

playAd();
The init() method automatically attempts autoplay using the “Nuclear Mute” strategy (muted + playsinline + autoplay). If autoplay fails (rare on TVs), an interactive overlay will appear.

Complete Example

Here’s a complete working example:
import { AdgentSDK, AdProgress, AdError } from 'adgent-sdk';

// Initialize the SDK
const sdk = new AdgentSDK({
  container: document.getElementById('ad-container')!,
  vastUrl: 'https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=',
  
  // Configuration
  targetBitrate: 2500,
  skipOffset: 5,
  skipButtonText: 'Skip Ad',
  debug: true,
  
  // Event handlers
  onStart: () => {
    console.log('✅ Ad playback started');
    // Pause main content, hide controls, etc.
  },
  
  onProgress: (progress: AdProgress) => {
    const { currentTime, duration, percentage, quartile } = progress;
    console.log(`⏱️ Progress: ${currentTime.toFixed(1)}s / ${duration.toFixed(1)}s (${percentage.toFixed(1)}%)`);
  },
  
  onComplete: () => {
    console.log('✅ Ad completed successfully');
    sdk.destroy(); // Clean up resources
    // Resume main content playback
  },
  
  onSkip: () => {
    console.log('⏭️ User skipped the ad');
    sdk.destroy();
    // Resume main content playback
  },
  
  onError: (error: AdError) => {
    console.error('❌ Ad error:', error.message, `(code: ${error.code})`);
    sdk.destroy();
    // Resume main content playback as fallback
  },
  
  onClick: (url: string) => {
    console.log('🖱️ Ad clicked:', url);
    // Opens URL in external browser on Smart TV
  },
  
  onClose: () => {
    console.log('🔙 User pressed Back button');
    sdk.destroy();
    // Resume main content
  }
});

// Initialize and play
async function playAd() {
  try {
    await sdk.init();
    console.log('🎬 Ad initialized and playing');
  } catch (error) {
    console.error('Failed to initialize ad:', error);
  }
}

playAd();

What Happens Under the Hood

When you call sdk.init(), Adgent SDK performs the following steps:
1

Fetch VAST XML

Downloads the VAST document from the provided URL with a 10-second timeout
2

Parse and resolve wrappers

Parses the XML and follows wrapper chains up to 5 levels deep, aggregating tracking pixels
3

Select best media file

Analyzes available media files and selects the optimal one based on:
  • Codec compatibility (H.264 > H.265 > VP9)
  • Bitrate matching (closest to targetBitrate: 2500 kbps)
  • Resolution preference (1080p preferred, 4K penalized)
  • Container format (MP4 preferred)
4

Create video element

Generates an HTML5 <video> element with platform-specific attributes:
  • muted (for autoplay compliance)
  • playsinline (for iOS/mobile platforms)
  • autoplay (attempts immediate playback)
  • crossorigin="anonymous" (for CDN content)
5

Setup UI components

Creates:
  • Skip button (appears after skipOffset seconds)
  • Progress indicator (top-left “Ad • 1 of 1 • 0:30” counter)
  • Focus trap (captures remote control keys)
6

Attempt autoplay

Tries to play the video automatically. If autoplay fails:
  • Shows an interactive overlay with a play button
  • Waits for user interaction (Enter key or click)
  • Fires impression pixels only after playback actually starts
The “Nuclear Mute” strategy (muted + playsinline + autoplay) achieves near-100% autoplay success on Smart TV platforms, with the interactive overlay as a graceful fallback.

Testing Your Integration

Use this test VAST URL for development:
https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=
This is Google’s test VAST tag that returns a 30-second linear video ad.

Common Issues

Solution: This is expected behavior on some platforms. The SDK automatically shows an interactive overlay when autoplay fails. Ensure your container is visible and the user can interact with it.
// The SDK handles this automatically
// If autoplay fails, an overlay with a play button appears
Solution: Ensure your container has explicit width and height styles and position: relative:
<div id="ad-container" style="width: 1920px; height: 1080px; position: relative;"></div>
Solution: The VAST tag may contain only VPAID or unsupported formats. Adgent SDK filters out VPAID and selects H.264/VP9 video files. Verify your VAST contains standard MP4 media files.
Solution: Check if the VAST includes a skipoffset attribute, or set one manually:
const sdk = new AdgentSDK({
  skipOffset: 5, // Force skip after 5 seconds
  // ...
});

Next Steps

Now that you have a working ad player, explore these advanced features:

Event Handling

Learn about all available events and callbacks

Configuration Options

Customize bitrate, timeouts, skip behavior, and more

Platform Adapters

Platform-specific features for WebOS, Tizen, and Vidaa

API Reference

Complete API documentation

Build docs developers (and LLMs) love