@directo/adunit
v1.0.5
Published
<img alt="version" src="https://img.shields.io/badge/version-0.0.0-blue?style=flat" /> <a href="https://getdirecto.com" target="_blank"> <img alt="getdirecto.com" src="https://img.shields.io/badge/getdirecto-join-brightgreen?style=flat" /> </a>
Downloads
855
Readme
Directo adUnit Integration Guide
Overview
This guide provides comprehensive instructions for integrating the Directo adUnit Library into your browser extension projects. It covers installation, background/content setup, required permissions, message filtering, API usage, and troubleshooting.
Installation Methods
Method 1: NPM Installation
- Install the package from npm:
npm install @directo/adunit- Import the library in your code:
// In background scripts
import { initializeAdUnit, isAdUnitMessage } from '@directo/adunit/background';
// In content scripts
import { initializeAdUnit } from '@directo/adunit/content';- Use your bundler of choice (Vite, webpack, Rollup, esbuild) to build your extension.
TypeScript Compatibility Note: This package is bundled with the ES2023 library and targets ES6. Ensure your project's TypeScript configuration (tsconfig.json) is compatible with these settings for optimal type support and compatibility.
@todo
Method 2: Direct Script Inclusion
- Obtain the Directo library JS builds from the
directo-globalfolder:
directo-global/background.js – for background/service worker
directo-global/content.js – for content scripts
Place these files in your extension (e.g., vendor/).
Reference them in manifest.json and your entry points:
{
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"vendor/directo-global/content.js",
"content.js"
]
}
]
}Implementation Guide
Background Script
After installing via NPM or including the JS file:
// For JS inclusion only (Method 2):
// self.importScripts('vendor/directo-global/background.js');
// globalThis.DirectoAdUnit.initializeAdUnit('YOUR_PARTNER_API_KEY');
// Using an IIFE for error handling isolation in the service worker context
(() => {
try {
// Initialize the Directo adUnit with your partner API key
initializeAdUnit('YOUR_PARTNER_API_KEY');
console.log('Directo background initialized successfully');
} catch (err) {
console.error('Failed to initialize Directo:', err);
// Optional: fallback logic
}
})();The background process bootstraps the Directo runtime, sets up listeners, and coordinates content activity.
Content Script
async function initializeContent() {
if (document.body) {
try {
console.log('Attempting to initialize Directo AdUnit');
await initializeAdUnit();
console.log('Directo AdUnit initialized successfully');
} catch (error) {
console.error('Error initializing Directo AdUnit:', error);
}
} else {
console.warn('Document body not available yet');
setTimeout(initializeContent, 50);
}
}
if (document.readyState === 'loading') {
console.log('Document still loading, waiting for DOMContentLoaded');
document.addEventListener('DOMContentLoaded', initializeContent);
} else {
console.log('Document already loaded, running initialization immediately');
initializeContent();
}Initialize the AdUnit early, once the DOM is ready, to ensure timely UI/display behavior.
Required Permissions
Exception requested: the required extension permissions for this Directo integration are storage and unlimitedStorage
{
"permissions": [
"storage",
"unlimitedStorage"
],
"host_permissions": [ "<all_urls>" ]
}Permission explanation
- storage: persists configuration and user preferences used by the AdUnit/runtime.
- unlimitedStorage (optional but recommended): if your combined extension + Directo data may exceed 10 MB; expect several MB used by cached rules/assets.
Ensure your injection strategy (e.g., content scripts declared in manifest.json) aligns with this permissions model.
Critical Integration Requirements
Auto-Rejecting Directo Messages
⚠️ IMPORTANT: Your extension must short-circuit Directo internal messages in your message listener to avoid conflicts with your own app messages.
// If using the package:
import { isAdUnitMessage } from '@directo/adunit/background';
// Example message listener (service worker / background)
chrome.runtime.onMessage.addListener((data, sender, sendResponse) => {
// Always gate Directo messages first:
if (isAdUnitMessage(data)) {
return; // Ignore: handled internally by Directo
}
// Your extension's message handling below...
});Why this is required
Without this guard:
Your extension might process Directo’s internal messages.
Directo functionality could break or behave unpredictably.
You may see console errors or crashes stemming from message handling.
API Reference
Background Script API
initializeAdUnit('YOUR_PARTNER_API_KEY');Content Script API
// Sets up the Directo AdUnit and observers
initializeAdUnit();Implement robust try/catch (or .catch) around initialization to surface failures and enact fallbacks. Both functions return promises that should be fire-and-forget, however we encourage handling initialization errors.
Error Handling
initializeAdUnit('YOUR_PARTNER_KEY')
.then(() => {
console.log('Directo background initialized successfully');
})
.catch((error) => {
console.error('Failed to initialize Directo:', error);
// Add any cleanup or degraded-mode logic here
});Testing Your Integration
Confirm the background script initializes without errors (Service Worker logs).
Navigate to pages where the AdUnit should activate and verify expected UI/behavior.
Troubleshooting
Common issues
Initialization Failures: Usually invalid/absent API key or network errors.
Missing AdUnit UI: Ensure content scripts are injected as expected (manifest matches) and that DOM is ready before calling initializeAdUnit().
Console Errors: Inspect logs from both background and content scripts.
Minimum Version: Confirm compatibility with the minimum Directo library version intended for this integration.
Support
For technical support or integration questions, contact [email protected].
License
Proprietary - Directo Tech, Inc.
