npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@directo/adunit

v3.1.5

Published

<a href="https://www.npmjs.com/package/@directo/adunit" target="_blank"> <img alt="Latest version" src="https://img.shields.io/npm/v/%40directo%2Fadunit?style=flat" /> </a> <a href="https://getdirecto.com" target="_blank"> <img alt="getdirecto.com" sr

Downloads

1,992

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

  1. Install the package from npm:
npm install @directo/adunit
  1. 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';
  1. 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.

Browser Support: Chrome, Firefox, and Safari 16.4 or later (the first Safari release with full Manifest V3 support). Browser differences are handled internally at runtime; no build-time configuration or polyfill is required from the integrating extension.

Method 2: Direct Script Inclusion

  1. Obtain the Directo library JS builds from the directo-global folder:
  • directo-global/background.js – for background/service worker

  • directo-global/content.js – for content scripts

  1. Place these files in your extension (e.g., vendor/).

  2. 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

Separate Background and Content Entrypoints

@directo/adunit ships two distinct entrypoints: @directo/adunit/background for the service worker and @directo/adunit/content for content scripts. They are not interchangeable:

  • The background entrypoint uses background-only Chrome APIs (e.g. chrome.runtime.onInstalled for config migration purposes on extension updates) that are unavailable in content scripts.
  • The content entrypoint runs in the page context and uses DOM/page APIs that are unavailable in the service worker.

⚠️ Do not pull the background entrypoint into a content-script bundle, or vice versa — even transitively through a shared module. Make sure your bundler configuration produces fully separated bundles for each entrypoint, and avoid sharing modules between them that re-export from @directo/adunit/background or @directo/adunit/content.

How to spot a misbundling

@directo/adunit detects when its background or content module is evaluated in the wrong execution context and reports it in the browser's devtools. Specifically, you will see one of the following console.error messages, followed by a console.trace showing the import chain that pulled the offending module in:

  • [Directo] @directo/extension-core/background was loaded outside a service-worker / background-page context… — background-only code ended up in a content script (or another extension page like the popup/options).
  • [Directo] @directo/extension-core/content was loaded inside a service-worker / background-page context… — content-only code ended up in the background bundle.

Both messages also tell you that they are likely caused by transitive imports and point back to this section of the README. To diagnose the offending import chain:

  1. Open devtools on the failing context: for content scripts use the page's devtools; for the service worker / background page use chrome://extensions → "Inspect views: service worker" (or the equivalent in Firefox's about:debugging).
  2. Find the [Directo] … console.error and expand the console.trace immediately below it. The stack frames are the modules that were mid-evaluation when the misuse was detected, walking back to your bundle's entrypoint.
  3. Enable source maps in your bundler's build configuration (devtool: 'source-map' in webpack, sourcemap: true in Rollup/Vite/esbuild). Without source maps the trace frames point at minified bundle internals; with them they point at the actual import lines in your source.
  4. Fix the import chain: usually this means moving a shared helper into a module that doesn't transitively re-export from @directo/adunit/background or @directo/adunit/content, or splitting it into background-safe and content-safe halves.

When this misuse is detected the SDK suppresses the Chrome API calls that would otherwise crash the host script, so seeing the warning does not necessarily mean the script will fail outright — but some functionality will be silently disabled. Treat the warning as a build bug and fix it.

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, unlimitedStorage and scripting.

{
  "permissions": [
    "storage",
    "unlimitedStorage",
    "scripting"
  ],
  "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.
  • scripting: needed to power core on-page features, like showing deal widgets on supported travel sites in real time.

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 messages in your message listeners to avoid conflicts with your own app messages. This applies to both chrome.runtime.onMessage and chrome.runtime.onMessageExternal.

⚠️ Initialize the background early: call initializeAdUnit(...) during the service worker's first synchronous turn (as in the example above, not behind an await), so your extension answers sibling messages from the moment it wakes up.

// If using the package:
import { isAdUnitMessage } from '@directo/adunit/background';

// Example message listeners (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...
});

chrome.runtime.onMessageExternal.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:

  1. Your extension might process Directo’s internal messages.

  2. Directo functionality could break or behave unpredictably.

  3. You may see console errors or crashes stemming from message handling.

API Reference

Background Script API

// Bootstraps the Directo runtime, message handling, and cross-extension coordination
initializeAdUnit('YOUR_PARTNER_API_KEY');

// Whether a message is addressed to Directo (any channel) and should be ignored by your listeners
isAdUnitMessage(message); // -> boolean

Content Script API

// Sets up the Directo AdUnit and observers, and resolves with the content API
const { onOffers } = await 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.

initializeAdUnit() can be called more than once in the same content script: every call returns the same initialization.

Placing Directo offers in your own UI

onOffers lets you add Directo's offer buttons wherever they fit your extension's UI: inside your own panel or modal, next to your buttons, in one place or several. Directo tells you when there is something to show and gives you a mount function to render it into your elements; it resolves the listing, stay dates, guests and prices on its own.

Offers are only available on pages Directo recognises as a single listing: the detail (hotel/property) and checkout views of the supported platforms. Those are the pages where Directo can extract the listing and stay parameters itself; anywhere else the state is inactive.

import { initializeAdUnit } from '@directo/adunit/content';

const { onOffers } = await initializeAdUnit();

const stop = onOffers((offers) => {
  switch (offers.status) {
    case 'loading':
    case 'available':
      // Directo's skeleton while loading, then its offer button
      offers.mount(slot, { maxItems: 1 });
      return () => {
        // Optional: runs when this state ends, after Directo removed what it mounted
      };
    default: // 'inactive' | 'empty'
      showYourOwnCta();
  }
});

// When your UI goes away for good
stop();

States:

  • inactive: nothing can be shown on this page (not a detail or checkout view, or Directo is not active here).
  • loading: offers are being fetched for the listing and stay on screen. mount renders Directo's loading skeleton.
  • available: at least one offer can be shown. mount renders the offer button(s).
  • empty: everything was fetched and there is nothing to show.

Behaviour:

  • The callback is called synchronously with the current state, then again whenever the status, the listing or its stay change, for example when the user navigates to another listing or changes the dates. Refetches of the same stay do not call it again: mounted buttons update themselves.
  • Each call opens a scope. Before the next call, Directo removes everything mounted in the current scope, then runs the function your callback returned. Mount again from the next call if you still want Directo's UI.
  • mount(target, { maxItems, vertical, styles }) appends Directo's UI to target and returns a function to remove it early. It stays valid for the whole scope, so you can keep it and mount later, for example once your own UI is built. Once the scope ended it renders nothing and returns null. maxItems (default 1) is the number of buttons; vertical (default true) stacks them, false lays them out in a row; styles is extra CSS injected into Directo's shadow root, to fit its UI into your layout.
  • Keep callbacks short: they run as part of Directo's navigation handling. Errors thrown by your callback or cleanup are caught and logged.
  • onOffers only exists on the API returned by initializeAdUnit(). Each content-script bundle has its own copy of the SDK, so call both from the same bundle.
  • Clicks are handled by Directo (new tab, Directo attribution). Directo stops the propagation of those clicks inside its shadow root, so if you track clicks on your element yourself, listen in the capture phase: slot.addEventListener('click', handler, { capture: true }).

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

  1. Confirm the background script initializes without errors (Service Worker logs).

  2. 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.