We recommend using the Javascript SDK, however if you need more control over ad rendering and tracking, you can use this version.

This Javascript SDK provides more control over ad rendering and tracking. It uses the same core functionality as the Javascript SDK but gives you responsibility for DOM manipulation and view tracking.

1. Import the SDK

A detailed overview of the SDK can be found in the SDK Reference.

<script type="module">
  import { fetchAd, markAdAsViewed } from 'https://server.megabrain.co/sdk/js';
</script>

2. Setup Parameters

Use the same parameters as the Javascript SDK, but omit the element property since you’ll handle rendering yourself

const fetchAdParams = {
  publisherToken: "your-token",
  code: "your-code",
  userId: "user-uuid",
  conversationId: "conversation-id",
  logLevel: "debug",
  messages: messages // Your message array
}

3. Handle Rendering and Tracking to display the ad

Create a container element and use the callbacks to manage content and tracking

const container = document.getElementById("ad-container");

fetchAd(fetchAdParams, {
  onToken: (token) => {
    // Handle each token as it arrives
    container.innerHTML += token; // Or use your preferred rendering method
  },
  onComplete: (content, metadata) => {
    // Setup visibility tracking
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          markAdAsViewed(metadata.impressionId);
        }
      });
    });
    observer.observe(container);
  },
  onError: (error) => {
    console.error('Ad fetch failed:', error);
  },
  onAdClick: (impression) => {
    // Handle ad clicks
    console.log('Ad clicked:', impression);
  }
});

Important Notes

  • You are responsible for rendering the markdown content into HTML
  • The markAdAsViewed function should be called only when the ad is fully visible in the viewport
  • Consider debouncing the intersection observer callback if needed