New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

adtrust

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

adtrust

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

latest
Source
npmnpm
Version
0.0.4
Version published
Maintainers
1
Created
Source

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)

ParameterData AttributeTypeDefaultDescription
iddata-idStringAuto-generatedUnique identifier for the ad
containerIddata-container-idStringnullID of container element. If not provided, one will be created
widthdata-widthNumbernullWidth of ad in pixels
heightdata-heightNumbernullHeight of ad in pixels
clickUrldata-click-urlStringnullURL to navigate to when ad is clicked
delaydata-delayString/Number"0"Delay in ms before loading the ad. Can include units: "2s", "500"
adTypedata-typeString"banner"Type of ad: "banner", "html", "tag", "video"

Viewability Parameters

ParameterData AttributeTypeDefaultDescription
viewabilityThresholddata-viewability-thresholdNumber0.5Percentage of ad that must be visible (0.0-1.0)
viewabilityTimedata-viewability-timeNumber1000Time in ms ad must be visible to count as viewable
heartbeatIntervaldata-heartbeat-intervalNumber250Interval in ms for checking viewability
lazyLoadThresholddata-lazy-load-thresholdNumber1Screen heights away from viewport to trigger lazy loading
refreshIntervaldata-refresh-intervalNumber30000Time in ms between ad refreshes if enabled
enableRefreshdata-enable-refreshBooleanfalseWhether to automatically refresh the ad
logViewabilityEventsdata-log-viewabilityBooleanfalseWhether to log viewability events to console
reportEndpointdata-report-endpointStringnullURL to send viewability beacons to

Global Configuration

ParameterTypeDefaultDescription
logErrorsBooleantrueLog errors to console
detectAdBlockerBooleantrueDetect ad blockers on initialization
adBlockerDetectedCallbackFunctionnullFunction to call if ad blocker is detected
onErrorCallbackFunctionnullFunction to call on errors
debugBooleanfalseEnable debug mode with verbose logging
autoInitBooleantrueAutomatically initialize ads from script tags

Banner Ad Parameters

ParameterData AttributeTypeRequiredDescription
imageUrldata-image-urlStringYesURL of the image to display
imageObjectFitdata-image-object-fitStringNoCSS object-fit property for the image (cover, contain, etc.)
imageAltTextdata-image-alt-textStringNoAlt text for the image for accessibility

HTML Ad Parameters

ParameterData AttributeTypeRequiredDescription
htmlContentdata-html-contentStringYes*HTML content to display (*or use template)
htmlTemplateIddata-html-template-idStringYes*ID of script tag containing HTML template (*or use content)
useSandboxdata-use-sandboxBooleanNo (true)Whether to use iframe sandbox for security

Third-Party Tag Ad Parameters

ParameterData AttributeTypeRequiredDescription
tagUrldata-tag-urlStringYesURL of the third-party ad tag
useSandboxdata-use-sandboxBooleanNo (true)Whether to use iframe sandbox for security

Video Ad Parameters

ParameterData AttributeTypeRequiredDescription
videoUrldata-video-urlStringYesURL of the video to play
posterUrldata-poster-urlStringNoURL of the poster image to show before play
autoplaydata-autoplayBooleanNo (false)Whether to autoplay the video
controlsdata-controlsBooleanNo (true)Whether to show video controls
muteddata-mutedBooleanNo (true)Whether to mute the video
loopdata-loopBooleanNo (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:

EventDescription
adTrust:loadedAd content has loaded
adTrust:loadErrorError loading ad content
adTrust:delayCompleteDelay timer completed
adTrust:viewableStartAd began to be viewable
adTrust:viewableEndAd is no longer viewable
adTrust:viewableImpressionAd has been viewable for required time
adTrust:viewQuartileAd reached viewability quartile (25%, 50%, 75%, 100%)
adTrust:clickAd was clicked
adTrust:videoReadyVideo is ready to play
adTrust:videoStartVideo started playing for the first time
adTrust:videoPlayVideo started or resumed playing
adTrust:videoPauseVideo was paused
adTrust:videoQuartileVideo reached playback quartile (25%, 50%, 75%)
adTrust:videoCompleteVideo completed playback
adTrust:videoErrorError 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.

Keywords

ads

FAQs

Package last updated on 05 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts