Skip to main content

JavaScript Demo

See how easy it is to integrate high-performance ads into your web app using our lightweight SDK.

Getting started

The JavaScript SDK is designed for any web environment where you can run JavaScript in the browser: static HTML pages, custom chat UIs, or full SPA frameworks. You only need:
  • A publisher account (to get your publisherToken and placement code)
  • A way to access your chat messages (with id, role, content, createdAt)

1. Include the SDK

You will need a publisher account to obtain your publisherToken and placement code.
Load the SDK from our CDN:
<script src="https://server.megabrain.co/sdk/js?type=global&publisherToken={publisherToken}"></script>
Don’t forget to replace {publisherToken} with your actual publisher token.

2. Initialize the SDK

The SDK is available as a global variable window.KontextSdk. Import KontextAds() to create an SDK instance and then createSession() to configure a session for a specific user and conversation.
const { KontextAds } = window.KontextSdk
const ads = KontextAds()

const session = ads.createSession({
  publisherToken: '<your-publisher-token>', // from Kontext dashboard
  userId: 'user-1234',                      // stable identifier for this user
  conversationId: 'conv-5678',              // unique ID of the chat or thread
  onEvent: ({ name, code, payload }) => {
    console.log('Ad event:', name, code, payload)
    // You can send events to your analytics here
  }
})
Notes:
  • userId should stay the same for the same user across sessions/devices if you want better personalization and frequency capping.
  • conversationId should be unique per chat thread or dialog (e.g. a specific chat room, support ticket, or conversation in your app).

3. Add user and assistant messages to the session

For Kontext to decide when and where to show an ad, it needs the conversation history. Add every message (both user and assistant) to the session as it appears.
// User message
session.addMessage({
  id: 'msg-1',
  role: 'user',                     // 'user' or 'assistant'
  content: 'Hello, how are you?',
  createdAt: new Date()
})

// Assistant reply
session.addMessage({
  id: 'msg-2',
  role: 'assistant',
  content: 'I am good, thank you!',
  createdAt: new Date()
})
Notes:
  • id must be unique per message and stable (do not change it later).
  • The same messageId will be used later when you render an ad for that message.
  • You should call session.addMessage() every time a new message appears in your chat UI.

4. Display ads

To display an ad, call session.render() with:
  • messageId: the ID of the assistant message you want to attach the ad to
  • element: the DOM node where the ad iframe will be injected
<div id="ad-container"></div>

<script type="module">
  // ... KontextAds(), session, and messages from previous steps

  const element = document.getElementById('ad-container')

  session.render({
    messageId: 'msg-2', // must match the assistant message ID
    element             // DOM element where the ad will be rendered
  })
</script>
How it works:
  • Kontext will select the best ad for the latest assistant message that has a matching bid.
  • The ad is rendered as an <iframe> inside element and is fully managed by the SDK.
  • You can create different containers (e.g. one below each assistant message) and call session.render() with a different messageId and element to show multiple ads within the same conversation.
In a real chat UI, you will typically:
  1. Render your message list.
  2. For each assistant message, create a corresponding <div> for the ad.
  3. Call session.render({ messageId, element }) once the message DOM has been mounted.
<div class="message">
  <p>I am good, thank you!</p>
  <div id="ad-msg-2"></div>
</div>

<script type="module">
  const element = document.getElementById('ad-msg-2')

  session.render({
    messageId: 'msg-2',
    element
  })
</script>

API documentation

KontextAds().createSession(options)session

Creates an ad session tied to a specific user and conversation.
publisherToken
string
required
Your publisher token used to fetch ads.
userId
string
required
Unique identifier for the user. Must remain stable across visits for personalization, frequency capping, and rewarded ads.
userEmail
string
Email of the user.
conversationId
string
required
Unique ID of the conversation or chat thread.
placementCode
string
Placement codes available in this conversation. Default: inlineAd.
character
object
Character metadata used for contextual ad selection and personalization.
regulatory
object
Regulatory object used in this conversation.
variantId
string
Publisher-provided identifier for the user cohort (for A/B testing).
onEvent
function
Callback triggered when an event occurs. See Supported events for more details.

session.addMessage(message)

Add a chat message. Every message must have the following properties:
id
string
required
Unique ID of the message.
role
string
required
Message role — must be user or assistant.
content
string
required
Text content of the message.
createdAt
Date
required
Timestamp of message creation.

session.render(options) → displays an ad

Renders an inline ad as an <iframe> into a specific DOM container.
messageId
string
required
ID of the assistant message the ad should be anchored to.
element
HTMLElement
required
The container where the ad will be injected.

session.destroy() (optional)

Cleans up internal state.
Call this when your conversation screen unmounts or session ends.

Supported Events

ad.clicked

The user has clicked the ad.

ad.viewed

The user has viewed the ad.

ad.filled

Ad is available.

ad.no-fill

Ad is not available.

ad.render-started

Triggered before the first token is received.

ad.render-completed

Triggered after the last token is received.

ad.error

Triggered when an error occurs.

video.started

Triggered when the video playback starts.

video.completed

Triggered when the video playback finishes.