Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

adtrust

seunome13ISC0.0.4

AdTrust is a versatile JavaScript library designed for efficient ad delivery with built-in viewability tracking, multi-format support, and ad block detection.

ads, advertising, trust, verification, anti-fraud, ad-validation, javascript

readme

AdTrust

Versatile Ad Delivery Library

AdTrust is a lightweight yet powerful JavaScript library for ad delivery with comprehensive viewability tracking, multi-format support, and basic ad blocker detection.

Version

Features

  • Multiple Ad Formats: Support for banner, HTML, third-party tag, and video ads
  • IAB/MRC Compliant Viewability Tracking: Follows industry standards for viewable impressions
  • Lazy Loading: Efficient resource management with configurable thresholds
  • Auto-Refresh: Optional timed refresh for ads when they're in view
  • Ad Blocker Detection: Basic detection with customizable callbacks
  • Detailed Event Tracking: Comprehensive events for viewability metrics
  • Flexible Integration: Both declarative (HTML) and programmatic (JS) implementations

IAB/MRC Compliance

AdTrust implements IAB (Interactive Advertising Bureau) and MRC (Media Rating Council) viewability standards:

  • Display ads are considered viewable when 50% of pixels are in view for at least 1 second
  • Large display ads (>242,500 pixels) use 30% viewability threshold per IAB guidelines
  • Video ads require 50% of pixels in view for at least 2 seconds
  • Detailed quartile tracking (25%, 50%, 75%, 100%) for both viewability and video progress
  • Proper viewability measurement using IntersectionObserver API

Installation

<script src="https://unpkg.com/adtrust"></script>

Via NPM

npm install adtrust

Then import in your project:

import AdTrust from 'adtrust';
// or
const AdTrust = require('adtrust');

Usage

AdTrust supports both declarative (HTML) and programmatic (JavaScript) implementations.

Declarative Implementation (HTML)

Add script tags with data attributes to define ads:

<!-- Banner Ad -->
<script
  data-type="banner"
  data-image-url="https://example.com/ad.jpg"
  data-click-url="https://example.com"
  data-width="300"
  data-height="250">
</script>

<!-- HTML Ad -->
<script
  data-type="html"
  data-html-content="<div>My custom HTML ad</div>"
  data-width="300"
  data-height="250">
</script>

<!-- Third-Party Tag Ad -->
<script
  data-type="tag"
  data-tag-url="https://adserver.example.com/tag.html"
  data-width="300"
  data-height="250">
</script>

<!-- Video Ad -->
<script
  data-type="video"
  data-video-url="https://example.com/ad.mp4"
  data-poster-url="https://example.com/poster.jpg"
  data-width="640"
  data-height="360"
  data-autoplay="true"
  data-muted="true">
</script>

Programmatic Implementation (JavaScript)

Create ads programmatically:

// Banner Ad
AdTrust.createAd({
  adType: "banner",
  imageUrl: "https://example.com/ad.jpg",
  clickUrl: "https://example.com",
  width: 300,
  height: 250
});

// HTML Ad
AdTrust.createAd({
  adType: "html",
  htmlContent: "<div>My custom HTML ad</div>",
  width: 300,
  height: 250
});

// Third-Party Tag Ad
AdTrust.createAd({
  adType: "tag",
  tagUrl: "https://adserver.example.com/tag.html",
  width: 300,
  height: 250
});

// Video Ad
AdTrust.createAd({
  adType: "video",
  videoUrl: "https://example.com/ad.mp4",
  posterUrl: "https://example.com/poster.jpg",
  width: 640,
  height: 360,
  autoplay: true,
  muted: true
});

Configuration Parameters

Common Parameters (All Ad Types)

Parameter Data Attribute Type Default Description
id data-id String Auto-generated Unique identifier for the ad
containerId data-container-id String null ID of container element. If not provided, one will be created
width data-width Number null Width of ad in pixels
height data-height Number null Height of ad in pixels
clickUrl data-click-url String null URL to navigate to when ad is clicked
delay data-delay String/Number "0" Delay in ms before loading the ad. Can include units: "2s", "500"
adType data-type String "banner" Type of ad: "banner", "html", "tag", "video"

Viewability Parameters

Parameter Data Attribute Type Default Description
viewabilityThreshold data-viewability-threshold Number 0.5 Percentage of ad that must be visible (0.0-1.0)
viewabilityTime data-viewability-time Number 1000 Time in ms ad must be visible to count as viewable
heartbeatInterval data-heartbeat-interval Number 250 Interval in ms for checking viewability
lazyLoadThreshold data-lazy-load-threshold Number 1 Screen heights away from viewport to trigger lazy loading
refreshInterval data-refresh-interval Number 30000 Time in ms between ad refreshes if enabled
enableRefresh data-enable-refresh Boolean false Whether to automatically refresh the ad
logViewabilityEvents data-log-viewability Boolean false Whether to log viewability events to console
reportEndpoint data-report-endpoint String null URL to send viewability beacons to

Global Configuration

Parameter Type Default Description
logErrors Boolean true Log errors to console
detectAdBlocker Boolean true Detect ad blockers on initialization
adBlockerDetectedCallback Function null Function to call if ad blocker is detected
onErrorCallback Function null Function to call on errors
debug Boolean false Enable debug mode with verbose logging
autoInit Boolean true Automatically initialize ads from script tags
Parameter Data Attribute Type Required Description
imageUrl data-image-url String Yes URL of the image to display
imageObjectFit data-image-object-fit String No CSS object-fit property for the image (cover, contain, etc.)
imageAltText data-image-alt-text String No Alt text for the image for accessibility

HTML Ad Parameters

Parameter Data Attribute Type Required Description
htmlContent data-html-content String Yes* HTML content to display (*or use template)
htmlTemplateId data-html-template-id String Yes* ID of script tag containing HTML template (*or use content)
useSandbox data-use-sandbox Boolean No (true) Whether to use iframe sandbox for security

Third-Party Tag Ad Parameters

Parameter Data Attribute Type Required Description
tagUrl data-tag-url String Yes URL of the third-party ad tag
useSandbox data-use-sandbox Boolean No (true) Whether to use iframe sandbox for security

Video Ad Parameters

Parameter Data Attribute Type Required Description
videoUrl data-video-url String Yes URL of the video to play
posterUrl data-poster-url String No URL of the poster image to show before play
autoplay data-autoplay Boolean No (false) Whether to autoplay the video
controls data-controls Boolean No (true) Whether to show video controls
muted data-muted Boolean No (true) Whether to mute the video
loop data-loop Boolean No (false) Whether to loop the video

API Reference

Main Methods

// Create any type of ad
const adInstance = AdTrust.createAd(options);

// Initialize ads from script tags in the document
AdTrust.initFromTag();

// Initialize a specific script tag by selector
AdTrust.initSpecificTag('#my-ad-script');

// Get all ad instances
const allAds = AdTrust.getAdInstances();

// Get a specific ad by ID
const myAd = AdTrust.getAdById('my-ad-id');

// Load a delayed ad immediately
AdTrust.loadDelayedAdNow('my-delayed-ad-id');

// Load all delayed ads immediately
AdTrust.loadAllDelayed();

// Get aggregated metrics for all ads
const metrics = AdTrust.getAggregateMetrics();

// Destroy all ad instances
AdTrust.destroyAll();

// Set global configuration
AdTrust.setGlobalConfig({
  viewabilityThreshold: 0.6,
  refreshInterval: 60000,
  enableRefresh: true
});

// Enable/disable debug mode
AdTrust.setDebugMode(true);

Ad Instance Methods

// Load ad content (typically happens automatically)
adInstance.loadContent();

// Refresh the ad
adInstance.refresh();

// Get viewability metrics
const metrics = adInstance.getViewabilityMetrics();

// For video ads, get video-specific metrics
const videoMetrics = adInstance.getVideoMetrics();

// Destroy the ad instance
adInstance.destroy();

Events

AdTrust dispatches custom events on ad elements, which you can listen for:

document.addEventListener('adTrust:viewableImpression', function(e) {
  console.log('Ad viewable:', e.detail);
});

Available events:

Event Description
adTrust:loaded Ad content has loaded
adTrust:loadError Error loading ad content
adTrust:delayComplete Delay timer completed
adTrust:viewableStart Ad began to be viewable
adTrust:viewableEnd Ad is no longer viewable
adTrust:viewableImpression Ad has been viewable for required time
adTrust:viewQuartile Ad reached viewability quartile (25%, 50%, 75%, 100%)
adTrust:click Ad was clicked
adTrust:videoReady Video is ready to play
adTrust:videoStart Video started playing for the first time
adTrust:videoPlay Video started or resumed playing
adTrust:videoPause Video was paused
adTrust:videoQuartile Video reached playback quartile (25%, 50%, 75%)
adTrust:videoComplete Video completed playback
adTrust:videoError Error with video playback

Ad Blocker Detection

AdTrust includes basic ad blocker detection using a "bait" method:

// Set custom callback
AdTrust.setGlobalConfig({
  adBlockerDetectedCallback: function() {
    console.log('Ad blocker detected!');
    // Display alternative content or messaging
  }
});

// Check status in metrics
const metrics = AdTrust.getAggregateMetrics();
if (metrics.isAdBlockerSuspected) {
  // Handle ad blocker presence
}

Advanced Usage Examples

Using HTML Templates

<!-- Define template -->
<script id="my-html-ad" type="text/html">
  <div class="custom-ad">
    <h3>Special Offer!</h3>
    <p>Limited time only</p>
    <button>Learn More</button>
  </div>
</script>

<!-- Reference template in ad -->
<script data-type="html" data-html-template-id="my-html-ad"></script>

Global Configuration

// Set global configuration for all ads
AdTrust.setGlobalConfig({
  viewabilityThreshold: 0.7,
  refreshInterval: 60000,
  enableRefresh: true,
  logViewabilityEvents: true,
  reportEndpoint: 'https://analytics.example.com/beacons',
  adBlockerDetectedCallback: function() {
    console.log('Ad blocker detected');
  }
});

Custom Container Placement

<!-- Define a container -->
<div id="ad-container"></div>

<!-- Reference container in ad -->
<script data-type="banner"
  data-container-id="ad-container"
  data-image-url="https://example.com/ad.jpg">
</script>

YouTube Video Support

AdTrust supports YouTube videos in video ads:

AdTrust.createAd({
  adType: "video",
  videoUrl: "https://www.youtube.com/watch?v=VIDEO_ID",
  width: 640,
  height: 360,
  autoplay: true,
  muted: true
});

Browser Compatibility

AdTrust is compatible with all modern browsers:

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 16+
  • Opera 47+

Some features may require polyfills for older browsers:

  • IntersectionObserver
  • Custom Events
  • Promises

License

ISC License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.