Showing ads with the Tunnl Web SDK
Banner and video ads, automatic or under your page's control.
Overview
The Tunnl Web SDK shows ads on your pages. One script tag loads the SDK together with your site's configuration: its ad units, their format and the demand behind them. Your page decides where the ads go and, for the formats that need it, when they play.
Everything on this page runs through that single tag. There is nothing to install and no configuration to write in JavaScript: ad units, sizes, floors and demand are managed in the Tunnl console. The ready-to-paste code for your site and for each ad unit is shown there as well.
Quick start
1. Add the tag once per page, in <head>. It is asynchronous and never blocks rendering.
<script src="https://sdk.tunnl.com/v1/tag/YOUR_TAG_ID.js" async></script>2. Place a container where a banner should appear. Its id is the ad unit code from the console. That is all a banner needs: the SDK finds the container and renders an ad into it.
<div id="sidebar-1"></div>3. Talk to the SDK through the command queue. Because the tag loads asynchronously, window.tunnl may not exist yet when your code runs. Push functions onto tunnl.cmd: they run as soon as the SDK is ready, or immediately if it already is.
<script>
window.tunnl = window.tunnl || { cmd: [] };
tunnl.cmd.push(function () {
tunnl.on('fill', function (e) {
console.log(e.adUnitId, 'filled by', e.module, 'at', e.price);
});
});
</script>Concepts
Ad units and formats
An ad unit is one placement, identified by its code (for example sidebar-1). Its format decides how it is presented:
| Format | Type | Where it plays | Started by |
|---|---|---|---|
display | banner | a container on the page | the SDK, or your code |
outstream | video | a player inside a container | the SDK, or your code |
instream | video | over your own content <video> | your code |
interstitial | video | full screen | your code |
rewarded | video | full screen, the user opts in | your code |
tunnl.adUnits() lists the ad units of the tag with their format and sizes.
Two ways to show an ad
tunnl.display(code)- Runs the auction and shows the winner right away. This is what happens automatically for display and outstream units.
tunnl.request(code)thenad.show()- Runs the auction and preloads the winner without showing it, so it can appear instantly later. A video is already downloaded and ready to play. Use this for interstitial, rewarded and in-stream ads, and whenever the moment to show an ad matters.
What happens in an auction
Each ad unit has a chain of demand sources (exchanges, Google Ad Manager, …) configured in the console. With the waterfall strategy they are asked in order until one fills; with parallel they are all asked at once and the highest price wins. Either way your code sees one result: an ad, or no fill. A no fill is normal and your page should simply carry on without an ad.
Video
Video ads are loaded with Google's IMA SDK, which the Tunnl SDK loads on demand. Every video ad is preloaded: when tunnl.request() resolves with an ad, the creative is fetched and ready to play, so show() starts it without waiting.
ad.show() for interstitial and rewarded ads from a click handler (the "watch ad" button, the "next level" button); the SDK starts the player within that click.Outstream
An outstream unit plays in a container on the page, with no content video of your own. Give the container the player size; the player fills it:
<div id="player-1" style="width:640px;height:360px"></div>Like a banner, it renders automatically when the container is on the page, and data-tunnl-auto="false" with tunnl.display('player-1') puts it under your control. Depending on the demand source, the ad either waits for a click on the player (click-to-play) or starts muted on its own.
In-stream: pre-roll, mid-roll, post-roll
In-stream ads play over your own content player. Put the ad container on top of the <video>; it only takes clicks while an ad is playing, so your player's controls keep working before and after. The SDK pauses your content for the break and resumes it when the break ends (except after a post-roll).
<div style="position:relative;width:640px;height:360px">
<video id="content-video" src="movie.mp4" controls playsinline
style="width:100%;height:100%"></video>
<div id="preroll-1" style="position:absolute;inset:0;pointer-events:none"></div>
</div>Pre-roll: request the ad as the page loads and show it when the viewer presses play.
<script>
window.tunnl = window.tunnl || { cmd: [] };
tunnl.cmd.push(function () {
var video = document.getElementById('content-video');
tunnl.request('preroll-1', { video: video, position: 'preroll' }).then(function (ad) {
if (!ad) return; // no fill: the content just plays
video.addEventListener('play', function () {
if (!ad.ready) return; // expired meanwhile
video.pause();
ad.show(); // the content resumes after the break
}, { once: true });
});
});
</script>Mid-roll: request ahead of the cue point, show when the content reaches it.
tunnl.cmd.push(function () {
var video = document.getElementById('content-video');
var CUE = 300; // seconds into the content
var midroll = null, requested = false, played = false;
video.addEventListener('timeupdate', function () {
if (!requested && video.currentTime > CUE - 20) {
requested = true;
tunnl.request('preroll-1', { video: video, position: 'midroll' })
.then(function (ad) { midroll = ad; });
}
if (!played && video.currentTime >= CUE && midroll && midroll.ready) {
played = true;
midroll.show(); // pauses the content, resumes it afterwards
}
});
});Post-roll: request with position: 'postroll' and show it on the content's ended event. The content is not resumed afterwards.
tunnl.cmd.push(function () {
var video = document.getElementById('content-video');
var postroll = null;
tunnl.request('preroll-1', { video: video, position: 'postroll' })
.then(function (ad) { postroll = ad; });
video.addEventListener('ended', function () {
if (postroll && postroll.ready) postroll.show();
});
});Interstitial
A full-screen video at a natural break: between levels, before the next article, after a finished task. It covers the page, locks scrolling while it plays and gives the focus back afterwards. It closes when the ad ends or the viewer uses the creative's skip button.
<script>
window.tunnl = window.tunnl || { cmd: [] };
tunnl.cmd.push(function () {
var next = null;
function preload() {
tunnl.request('interstitial-1').then(function (ad) { next = ad; });
}
preload();
// call at a natural break; done() continues your flow
window.showInterstitial = function (done) {
if (!next || !next.ready) return done(); // nothing ready: carry on
next.show().then(function (result) { // resolves when it closes
next = null;
preload(); // ready for the next break
done();
});
};
});
</script>
<button onclick="showInterstitial(startNextLevel)">Next level</button>Rewarded
The user chooses to watch a full-screen ad in exchange for a reward. Offer the reward only when an ad is ready, and grant it only when result.rewarded is true: the ad was watched to the end. The player has a close button; closing early gives no reward.
<button id="watch-ad" type="button" hidden>Watch an ad for 50 coins</button>
<script>
window.tunnl = window.tunnl || { cmd: [] };
tunnl.cmd.push(function () {
var button = document.getElementById('watch-ad');
function preload() {
tunnl.request('rewarded-1').then(function (ad) {
if (!ad) return; // no fill: keep the offer hidden
button.hidden = false;
button.onclick = function () { // show() from the click
button.hidden = true;
ad.show().then(function (result) {
if (result.rewarded) grantCoins(50); // watched to the end
preload(); // get the next one ready
});
};
ad.on('expire', function () { // unused for 30 minutes
button.hidden = true;
preload();
});
});
}
preload();
});
</script>The outcome of show()
ad.show() resolves with { status, rewarded }:
status | Meaning |
|---|---|
rendered | Banner or outstream: the ad is on the page. show() resolves right away; the ad stays until it is refreshed or cleared. |
completed | The ad played to the end. |
skipped | The viewer used the creative's skip button. |
closed | The viewer closed it early (rewarded close button, Esc). |
error | Playback failed or the ad did not start within 10 seconds; the full-screen layer closes by itself. |
nofill | A preloaded banner whose Google Ad Manager ad, requested only now, did not fill, and nothing else in the auction did either. |
A preloaded banner from Google Ad Manager is only requested when you call show(): Ad Manager counts an impression as soon as its ad renders, so it is not fetched for an ad that might never be shown. If it does not fill then, the next demand of the auction is shown instead.
rewarded is true only for a rewarded ad with status completed.
Video events
Rewarded, watched to the end:
Rewarded, closed early:
Interstitial and in-stream:
Outstream:
click fires when the viewer clicks through to the advertiser. An ad that is never shown fires expire when its time runs out.
Keys
Keys tell what the ad runs with, for targeting and for reports by content, developer, publisher, placement or test group. There are five, the same on every site and app:
| Key | What | Example |
|---|---|---|
cid | the content: an article, a game, an app screen | 'game-4521' |
cowner | who made it: an author, a game developer or studio | 'studio-88' |
pubid | who publishes it: a game's publisher, a news agency | 'pub-12' |
adplace | where in the content the ad shows | 'level_end', 'menu', 'extra_life' |
abgroup | your A/B test group | 'b' |
Set them for the page, before or after the tag, and per ad:
<script>
window.tunnl = { cmd: [], keys: { cid: 'game-4521', cowner: 'studio-88' } };
</script>
<script async src="https://sdk.tunnl.com/v1/tag/YOUR_TAG_ID.js"></script>
<script>
tunnl.cmd.push(function () {
tunnl.setKeys({ cid: 'game-4522' }); // the next game (null removes a key)
tunnl.display('banner-1', { keys: { adplace: 'level_end' } }); // this ad only
});
</script>Video ads are usually requested ahead of time, and an ad takes the keys it was requested with, not those at show(). So pass keys to request(), next to its other options:
tunnl.cmd.push(function () {
// rewarded, shown on the "extra life" button
tunnl.request('rewarded-1', { keys: { adplace: 'extra_life' } }).then(function (ad) {
if (!ad) return;
button.onclick = function () {
ad.show().then(function (r) { if (r.rewarded) grantExtraLife(); });
};
});
// interstitial between levels, kept for 10 minutes
tunnl.request('interstitial-1', { ttl: 600000, keys: { adplace: 'level_end' } });
// pre-roll over the page's own player
tunnl.request('preroll-1', {
video: '#content-video',
position: 'preroll',
keys: { adplace: 'pre_game', abgroup: 'b' },
});
});- Request one ad per place: an ad requested for
extra_lifeis reported asextra_lifewherever it is shown. - When the content changes without a page load (a single-page app opens the next game), call
setKeys()and request new ads; drop the ones requested for the previous game withad.destroy().
Values are strings or numbers of up to 40 characters; " ' = ! + # * ~ ; ^ ( ) < > [ ] , & are removed. An ad takes the keys it was requested with. They reach Google Ad Manager as key-values under the same names, the exchange as the content of the bid request, and our reports. Do not put personal data (e-mail addresses, user ids) in keys.
Events
Subscribe to every ad of the page with tunnl.on, or to one ad with ad.on. Both return a function that unsubscribes.
tunnl.cmd.push(function () {
var off = tunnl.on('impression', function (e) {
analytics.track('ad_impression', { unit: e.adUnitId, format: e.format, source: e.module });
});
// later: off();
});Every payload carries:
| Field | |
|---|---|
adUnitId | ad unit code |
format | display, outstream, instream, interstitial or rewarded |
requestId | id of the auction; ties the events of one ad together |
module, network | the demand source that won: its type and the exchange / Ad Manager network it went through (not on request / nofill) |
keys | the keys the ad was requested with; absent when there are none |
test | true when the winner is a Google test ad (our development Ad Manager network); absent otherwise |
| Event | When | Formats | Extra fields | ad.on |
|---|---|---|---|---|
request | an auction starts | all | – | |
fill | an auction produced an ad | all | price (CPM) | – |
nofill | nothing filled | all | – | |
rendered | the ad is on the page | display, outstream | ✓ | |
impression | the ad is seen; trackers fire | all | ✓ | |
start | video playback started | video | ✓ | |
complete | a video ad played to the end | video | ✓ | |
skip | the viewer skipped | video | ✓ | |
click | click-through to the advertiser | video | ✓ | |
reward | the reward was earned | rewarded | ✓ | |
close | the ad break ended | instream, interstitial, rewarded | status, rewarded | ✓ |
expire | a preloaded ad ran out of time unused | all | ✓ | |
error | the auction, rendering or playback failed | all | error | ✓ |
Grant rewards from the show() result (or ad.on('reward')) rather than a global reward listener, so the reward is tied to the ad the user chose to watch.
API reference
window.tunnl
| Member | Returns | |
|---|---|---|
cmd.push(fn) | runs fn(tunnl) once the SDK is ready | |
display(code, options?) | Promise<Result | null> | auction and show; null on no fill |
request(code, options?) | Promise<Ad | null> | auction and preload |
refresh(code) | Promise<Result | null> | new auction for a unit shown with display() |
clear(code) | remove the ad shown in a container | |
displayAll() | Promise | render every automatic unit whose container is on the page |
adUnits() | [{ id, type, format, sizes }] | the tag's ad units |
on(event, fn) / off(event, fn) | unsubscribe function | events of every ad |
setKeys(keys) / getKeys() | the page's keys | see Keys |
getStats() | object | SDK version, tag, floors, queued analytics events |
version | string | SDK version |
Result is { module, network, price, status, rewarded }.
Options
| Option | For | |
|---|---|---|
container | display, outstream, instream | element or selector; default #<code>, then [data-tunnl-ad-unit="<code>"] |
video | instream | your content <video> (element or selector) |
position | instream | 'preroll' (default), 'midroll', 'postroll' |
width, height | all | override the ad unit's first size |
ttl | request() | milliseconds a preloaded ad stays usable; default 30 minutes |
keys | all | keys of this ad, over the page's (see Keys) |
Ad
| Member | |
|---|---|
show() | Promise<{ status, rewarded }>; an ad is shown once |
ready | true while it can still be shown |
expiresAt | timestamp (ms) after which it can no longer be shown |
adUnitId, format, requestId, module, price | what won |
on(event, fn) | events of this ad |
destroy() | discard it without showing |
show() rejects, with error.code, when the ad cannot be shown at all:
error.code | Meaning |
|---|---|
expired | older than its ttl; request a new one |
shown | it was already shown |
destroyed | destroy() was called |
busy | another full-screen ad is on screen |
HTML attributes
| Attribute | |
|---|---|
id="<code>" | marks the container of an ad unit |
data-tunnl-ad-unit="<code>" | the same, when the id is taken |
data-tunnl-auto="false" | no automatic rendering for this container |
Good practice
- Request early, show later. The auction and the video download happen while the user is busy, and the ad starts instantly when its moment comes.
- Show full-screen ads from a click. Otherwise the browser may block playback with sound.
- Plan for no fill. It is a normal outcome: collapse the slot, keep the flow going, and never promise a reward before an ad is ready.
- Reserve space. Give banner and video containers their size so the page does not jump when an ad arrives.
- Respect the moment. Interstitials at natural breaks only, rewarded ads only when the user asks, banners refreshed only while in view.
- Keep one tag per page, in
<head>, loaded withasync. A second copy of the tag is ignored.
Debugging
Turn on debug for the tag in the Tunnl console: the SDK then logs every auction, demand source and event to the browser console, prefixed with [tunnl].
https://sdk.tunnl.com/v1/tag/YOUR_TAG_ID/config.json shows the configuration the SDK received, and tunnl.getStats() its current state.
| Symptom | Likely cause |
|---|---|
window.tunnl has only cmd | the tag id is wrong, or the tag or site is disabled: the tag then serves an empty script |
| "container not found" in the console | no element with the ad unit code as id or data-tunnl-ad-unit, or it was added after the SDK looked; call tunnl.display() once it exists |
request() resolves with null | no fill for this request; frequent on a new site or with a high floor |
| video starts without sound or not at all | show() was not called from a user action |
show() rejects with expired | the ad was preloaded more than 30 minutes earlier; request a new one |