@playanext/playa-yield-sdk
v1.1.5
Published
PlayaYield Chrome Extension Ad Monetization SDK for Manifest V3
Downloads
637
Maintainers
Readme
@playanext/playa-yield-sdk
Production-ready Chrome Extension Ad Monetization SDK for Manifest V3
A lightweight, fully TypeScript-based SDK that allows Chrome extension developers to easily display ads and earn money through the PlayaYield platform. Built from the ground up for Manifest V3 compliance with zero remote script execution.
✨ Features
- 🚀 Manifest V3 Compliant - No remote script execution, all code bundled
- 📦 Lightweight - < 35 KB minified and tree-shakeable
- 🔒 Secure - All network requests routed through background service worker
- 🎯 Type-Safe - Full TypeScript support with excellent IDE autocomplete
- 🎨 Flexible - Returns ready-to-append HTML elements for full styling control
- 📊 Auto-Tracking - Automatic impression and click tracking with sendBeacon
- ✅ Consent-Ready - Built-in support for user consent callbacks
- 🧪 Environment Support - Configure test vs production via
envand/orbaseUrl
📦 Installation
npm install @playanext/playa-yield-sdk🚀 Quick Start
1. Initialize SDK in Background Service Worker
In your background.ts:
import { initializePlayaYield } from '@playanext/playa-yield-sdk';
// Initialize PlayaYield with your configuration
initializePlayaYield({
apiKey: 'your-api-key',
env: 'production',
consentCallback: async () => {
// Check user consent here
return await checkUserConsent();
},
});2. Configure manifest.json
Add the background service worker:
{
"manifest_version": 3,
"name": "Your Extension",
"version": "1.0.0",
"background": {
"service_worker": "background.js"
}
}3. Display Ads in Your Extension
In your content script, popup, or options page:
import { createAd } from '@playanext/playa-yield-sdk';
// No initialization needed! Just use createAd directly
const { element, impressionId } = await createAd({
placement: 'banner',
size: { width: 300, height: 250 },
categories: ['tech', 'gaming'],
});
// Append to your DOM
document.getElementById('ad-slot')!.appendChild(element);📚 API Reference
initializePlayaYield(config: SDKConfig): void
Initialize the PlayaYield SDK in your background service worker. Call this once with your API key and configuration.
Parameters:
interface SDKConfig {
apiKey: string; // Your PlayaYield API key (required)
env?: 'production' | 'test'; // Environment mode (default: 'production')
baseUrl?: string; // Custom API URL (optional, default: https://www.playayield.com)
}Example:
// background.ts
import { initializePlayaYield } from '@playanext/playa-yield-sdk';
initializePlayaYield({
apiKey: 'prod_abc123xyz',
env: 'production',
});createAd(options: AdOptions): Promise<AdResult>
Request and create an ad element. Returns a ready-to-append div element containing the ad HTML.
No initialization needed - just call this function from any content script, popup, or page. The SDK configuration is stored in the background worker.
Parameters:
interface AdOptions {
placement: 'internal' | 'popup' | 'sidebar' | string; // Ad placement type
size: { width: number; height: number }; // Ad dimensions
categories?: string[]; // Optional targeting
[key: string]: any; // Custom metadata
}Returns:
interface AdResult {
element: HTMLDivElement; // Ready-to-append div element
impressionId: string; // Unique impression ID
clickUrl?: string; // Optional click-through URL
}Example:
try {
const { element, impressionId } = await createAd({
placement: 'internal',
size: { width: 300, height: 250 },
categories: ['tech', 'productivity'],
});
document.getElementById('ad-container')!.appendChild(element);
console.log('Ad displayed:', impressionId);
} catch (error) {
console.error('Failed to load ad:', error);
}🎯 Common Use Cases
Banner Ad in Popup
// popup.ts
import { createAd } from '@playanext/playa-yield-sdk';
const { element } = await createAd({
placement: 'internal',
size: { width: 300, height: 250 },
});
document.getElementById('banner-slot')!.appendChild(element);Sidebar Ad in Content Script
// content.ts
import { createAd } from '@playanext/playa-yield-sdk';
// Create sidebar container
const sidebar = document.createElement('div');
sidebar.id = 'my-extension-sidebar';
document.body.appendChild(sidebar);
// Load ad
const { element } = await createAd({
placement: 'internal',
size: { width: 300, height: 250 },
});
sidebar.appendChild(element);Multiple Ad Placements
// Load multiple ads
const [ad1, ad2] = await Promise.all([
createAd({ placement: 'internal', size: { width: 300, height: 250 } }),
createAd({ placement: 'internal', size: { width: 300, height: 250 } }),
]);
document.getElementById('ad-slot-1')!.appendChild(ad1.element);
document.getElementById('ad-slot-2')!.appendChild(ad2.element);Custom Styling
const { element } = await createAd({
placement: 'internal',
size: { width: 300, height: 250 },
});
// Apply custom styles to the div container
element.style.borderRadius = '8px';
element.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
element.style.margin = '20px auto';
document.getElementById('ad-slot')!.appendChild(element);🧪 Test Mode
Use test mode during development to point your extension at a PlayaYield test environment.
// background.ts
import { initializePlayaYield } from '@playanext/playa-yield-sdk';
initializePlayaYield({
apiKey: 'dev_test_key',
env: 'test',
// If PlayaYield provides you a dedicated test API URL, set it here:
// baseUrl: 'https://<your-test-api-host>'
});Then in your content scripts/popups:
const { element } = await createAd({
placement: 'internal',
size: { width: 300, height: 250 },
});Note: The SDK does not generate local placeholder creatives in test mode. It still requests ads from the configured backend.
📊 Tracking
The SDK automatically tracks impressions and clicks:
- Impressions: Tracked when the ad element loads
- Clicks: Tracked when the user clicks on the ad
All tracking uses navigator.sendBeacon for fire-and-forget reliability, with automatic fallback to fetch if needed.
🏗️ Build Configuration
The SDK is built with tsup and outputs:
- ESM:
dist/index.mjs - CJS:
dist/index.js - Types:
dist/index.d.ts
All formats are tree-shakeable and optimized for minimal bundle size.
🔧 Advanced Configuration
Custom API Endpoint
// background.ts
initializePlayaYield({
apiKey: 'your-api-key',
baseUrl: 'https://custom-api.example.com',
});🐛 Error Handling
The SDK throws typed errors for different failure scenarios:
import { createAd } from '@playanext/playa-yield-sdk';
try {
await createAd({ placement: 'internal', size: { width: 300, height: 250 } });
} catch (error) {
switch (error.name) {
case 'NetworkError':
console.log('Network request failed');
break;
case 'ConfigError':
console.log('Invalid configuration');
break;
default:
console.log('Unknown error:', error);
}
}📝 Complete Example
See the example/ directory for a complete working Chrome extension that demonstrates:
- Background service worker setup
- Popup with ad display
- User controls for placement and size
- Error handling and status messages
- Beautiful UI with modern styling
To run the example:
cd example
npm install
npm run buildThen load the example/ directory as an unpacked extension in Chrome.
🤝 Support
- Documentation: https://docs.playanext.com
- API Reference: https://api.playanext.com/docs
- Issues: GitHub Issues
- Email: [email protected]
📄 License
MIT © PlayaYield
Made with ❤️ for Chrome extension developers
