SofAds SDK reference
The SofAds TV SDK shows interstitial, rewarded and QR ads in Smart TV apps and games on Samsung Tizen, LG webOS, Whale TV and Titan OS, and sends free usage analytics. It renders every ad as an overlay above your app, handles the remote while the ad is up, and never throws: every call settles within a fixed time.
The platform pages cover the files each TV needs: Tizen, webOS, Whale TV, Titan OS and Amazon Vega OS (Fire TV, in a WebView host app).
Install
You ship the SDK inside your app package: with npm from the pinned package on the SofAds CDN, or as sofads.min.js from your SofAds dashboard (Apps → Download SDK, which also shows the npm line and the checksums). It isn't on the public npm registry.
Script tag (recommended for TV store builds). Put sofads.min.js in your app package and load it from there. The script defines the global SofAds.
<script src="js/sofads.min.js"></script>npm. The SDK is an npm package with ESM, CommonJS and TypeScript types. It is not on the public npm registry: install the pinned version from the SofAds CDN, and your bundler puts the SDK in your build. package.json and the lockfile keep the URL and its integrity hash, so every install gets the same file:
npm install https://sdk.sofadsrv.com/sdk/v1.0.0/sofads-tv-sdk-1.0.0.tgzimport SofAds from "@sofads/tv-sdk";
SofAds.init({ appId: "sof_YOUR_APP_ID" });Hosted web apps (an app that loads its pages from your own website instead of a package) can load a pinned version from sdk.sofadsrv.com instead, never a moving "latest": <script src="https://sdk.sofadsrv.com/sdk/v1.0.0/sofads.min.js"></script>.
The SDK has no runtime dependencies and runs on Chrome 53 and later (ES2015), which covers TVs from 2017 on.
Quick start
SofAds.init({
appId: "sof_YOUR_APP_ID",
onPause: () => game.pause(), // stop your render loop before an ad plays
onResume: () => game.resume(), // always follows onPause
});
// At a natural break. The call always settles; your game just continues.
async function onLevelComplete() {
await SofAds.showInterstitial({ placement: "level_break" });
startNextLevel();
}
// The user chose to watch for a reward. addCoins is your own function.
function onExtraLifeButton() {
SofAds.showRewarded({
placement: "extra_life",
onReward: (reward) => addCoins(reward.amount),
});
}You don't need to wait for init before showing an ad: a show call made while init is still running waits for it, within its own timeout. Every call returns a promise, so you can await it or just call it.
init(options)
SofAds.init(options) starts the SDK and returns a promise of { status, platform, sdk, bootstrap?, reason? }, where status is "ready", "error" or "timeout". It is safe to call without await and calling it twice has no effect. It resolves within 5 seconds, also when the network is down.
| Option | Default | What it does |
|---|---|---|
appId | (required) | Your app ID from the dashboard: sof_ followed by 10 characters. An invalid ID makes init resolve error, and every show resolves error. |
onPause, onResume | none | Renderer handoff. Stop your render loop (Lightning, Blits, Pixi, a canvas loop) in onPause so video plays smoothly, and restart it in onResume. |
consent | {} | Consent known at start-up: { gdpr, tcf, gpp, gpp_sid, us_privacy, analytics, ads }. See consent. Passing consent turns the SofAds consent screen off. |
consentScreen | "auto" | The SofAds consent screen: "auto" asks once, right after init, where GDPR applies and your app passed no consent; "first-ad" asks right before the first ad instead; false never (you bring your own consent tool). |
test | false | Ask for test ads only. |
debug | false | Console logging. SofAds.debug(true) also shows the debug overlay. |
theme | { accent: "#7c5cff" } | The one accent color of the ad UI (focused button, QR frame). Hex, rgb() or hsl(). |
prefetch | none | [{ placement, type }]: fetch a backup ad for these placements right after init. A backup ad only shows when the live request at the break gets no answer in time. |
platform | detected | Force a platform. Use "web" only for a desktop or demo build; the SDK never guesses it. A web build always gets test ads, never real ads. |
appVersion, nativeAppId | read on Tizen and webOS | Your app version and store app ID, reported with requests and analytics. |
whale | none | Whale TV: the SDK reads the advertising ID itself. { getAdId } overrides it; { deviceInfoScript: false } stops the SDK from adding Whale's device info script. See Whale TV setup. |
titan | none | Titan OS: { getDeviceInfo } from the Titan SDK. See Titan OS setup. |
tmax | 1500 | Time budget of the ad server in ms (100 to 5000). |
endCardTimeoutSeconds | 0 | 0 keeps the end card until the user presses OK (so they can scan); a number closes it after that many seconds. |
container | document.body | The element the ad overlay mounts into. |
tizen | { avplayHandover: true } | Samsung Tizen apps that play video with AVPlay. avplayHandover: suspend your app's AVPlay for an ad and restore it afterwards; false means your app does it in onPause / onResume. avplayUrl: a function that returns the stream URL to restore, for live URLs that expire or an AVPlay opened before the SDK loaded (default: the URL passed to webapis.avplay.open()). See Video apps with AVPlay. |
SofAds.init({
appId: "sof_YOUR_APP_ID",
consent: { gdpr: 1, tcf: "CP_your_tcf_string" },
theme: { accent: "#1f8efd" },
});Showing ads
showInterstitial
SofAds.showInterstitial({ placement, startTimeoutMs? }) shows a full-screen ad at a natural break: between levels, after a game over, before the next episode. It resolves when the ad is gone (closed), not when it starts, or right away with no_fill when there is nothing to show. onPause and the show event tell you when an ad takes the screen.
async function betweenLevels() {
const r = await SofAds.showInterstitial({ placement: "level_break" });
if (r.status === "shown") {
// The ad was on screen; r.completed and r.skipped tell you how it ended.
}
startNextLevel();
}Ad before a video (pre-roll)
In a video app the viewer is waiting for the video they chose, so give the ad a short time to start with startTimeoutMs. When no ad screen has opened by then, the call resolves timeout and nothing appears later. An ad that did open plays to its end, however long it is. Start the video after the call resolves, whatever it returns.
async function openVideo(video) {
if (isAdBreakDue()) { // your own pacing, e.g. every 3rd video, never the first
await SofAds.showInterstitial({ placement: "preroll", startTimeoutMs: 3500 });
}
videoPlayer.play(video); // after the ad, whatever the result
}Put the ad break where a video is opened, not in code that also runs on a quality change, a stream retry or a fallback to another format, or those count as new videos and bring an ad in the middle of one.
Common mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Racing the show call against your own timer (Promise.race) | The show call resolves when the ad closes, so your timer fires while the ad plays and your video or game starts underneath it, both audible | startTimeoutMs on the show call |
| An ad break inside code that also handles retries, quality changes or "play again" | Ads in the middle of an activity, and more ads than you planned | Call it once, where the user starts something new |
| An interstitial right after a rewarded ad (revive, then game over) | Two or three ads in a row; most viewers skip them | Keep at least a minute between interstitials and any other ad |
Calling closeAd() soon after an ad started | The ad is cut off and isn't paid | Use closeAd() only when your app is closing or going to the background |
Turning on prefetch to have an ad "ready" | Nothing faster: every break asks for a live ad first, a prefetched one is only a fallback | Leave it out |
await SofAds.init() behind your splash screen | The app waits for the network | Don't await it; show calls wait for init themselves |
showRewarded
SofAds.showRewarded({ placement, reward?, onReward }) shows an ad the user chose to watch for a reward. Grant the reward in onReward: it is called exactly once, and only when the reward is earned (the video completed, or the QR code was scanned on a scan-to-reward ad). Closing early means no reward, and the screen says so.
SofAds.showRewarded({
placement: "extra_life",
onReward: (reward) => addCoins(reward.amount), // addCoins is your own function
});Rewarded ads are never skippable. On a scan-to-reward ad the QR card says "Scan to get +500 [icon]", polls for the scan and calls onReward the moment it is confirmed; the user then closes the ad with Continue.
App install ads
Interstitials can also show an app install ad: another TV app's video or screenshot with its icon, name and rating, and an Install button that has the focus from the start. Close appears after 5 seconds; the arrow keys move between Install and Close. When the ad ends, an end card shows the app once more. Only a press of Install opens the app's page in the TV's own store; nothing opens it by itself. Your app goes to the background while the store is open, as when the user presses the Home button, so pause and resume as you already do with onPause / onResume.
You don't call anything for it: the SDK asks for app install ads only where it can open the store.
| Platform | What it needs |
|---|---|
| LG webOS | application.launcher in requiredACG of appinfo.json (see webOS setup). An app whose requiredACG lacks it gets no app install ads. |
| Samsung Tizen | The privilege http://tizen.org/privilege/application.launch in config.xml (packaged apps; see Tizen setup). Without it, no app install ads. |
| Amazon Vega OS | The host app opens the Appstore link the page posts and sets openStore: true (see Vega OS setup). |
App install ads are never shown in rewarded placements, never inside the app they promote, and not to TVs that already have that app (when it uses SofAds too).
ShowResult
Every show call resolves with the same object. Most apps never need to read it.
| Field | Meaning |
|---|---|
status | "shown", "no_fill", "error" or "timeout". |
placement | The placement you asked for. |
completed | The ad was watched or displayed to the end. |
skipped | The user skipped (interstitial) or closed early (rewarded). |
rewarded | onReward was called for this ad. |
test | It was a test ad. |
format, ad_id | The format shown (vast, qr_card, ...) and an opaque ID for support tickets. |
reason, error_code | Diagnostics only, e.g. no_inventory or a VAST error code. |
store_opened | An app install ad: the user pressed Install and the TV's store page opens. Your app may go to the background. |
Rewards
The publisher owns the reward. You set it per placement in the dashboard (an amount, an icon and an optional name per language), and the ad screen shows it as +500 [icon]. The advertiser never writes reward text.
onReward receives the reward the user was shown:
| Field | Meaning |
|---|---|
amount | The amount the screen promised, e.g. 500. Absent when the placement has no amount and you passed none. |
name | The reward name in the ad's language, when there is one. |
reward | The full reward: { amount?, name?, icon_url? }. Absent when neither the placement nor your call set a reward (the screen then said "your reward"). |
placement, ad_id | Which placement and which ad. |
reward_on | "complete" (watched to the end) or "scan" (scan-to-reward). |
Override the amount or name for one call, for example when the reward depends on the level. The icon always comes from the placement settings:
function offerDoubleCoins(levelCoins) {
SofAds.showRewarded({
placement: "level_end",
reward: { amount: 2 * levelCoins, name: "coins" },
onReward: (reward) => addCoins(reward.amount || 2 * levelCoins),
});
}Events
SofAds.on(event, fn) subscribes to an event and returns a function that unsubscribes. once and off work as you'd expect. A listener that throws never breaks the SDK.
| Event | When |
|---|---|
ready | init finished. |
show | An ad overlay opened. |
impression | The ad was counted as seen. |
complete | The ad played or displayed to the end. |
skip | The user skipped (see skippable ads). |
store_open | An app install ad: the user pressed Install; { store: { platform, id } }. |
close | The overlay closed. Always follows show. |
reward | A reward was granted (onReward was called). |
no_fill | There was no ad for the request. |
error | An ad failed; the call resolved error. |
consent | The user answered the consent screen: { ads, analytics, via }, where via is "screen" (before an ad) or "menu" (showConsent()). |
const stop = SofAds.on("close", () => music.resume());
SofAds.once("ready", () => console.log("SofAds is ready"));
// Later, when the listener is no longer needed:
stop();Custom analytics events go through SofAds.track(name, props?). Names use lowercase letters, digits and underscores (up to 48 characters), with up to 20 flat properties:
SofAds.track("level_complete", { level: 3, stars: 2 });Consent
The SDK follows the consent your app collects. Pass what you know at start-up in init({ consent }), and call SofAds.setConsent() whenever it changes: the change is merged into the current state and applies from the next request. You may call it before init, for example when your consent tool answers early.
// From your consent tool (IAB TCF v2):
SofAds.setConsent({ gdpr: 1, tcf: "CP_your_tcf_string" });
// Or your own consent screen, without TCF:
SofAds.setConsent({ ads: false, analytics: true });| Field | Meaning |
|---|---|
gdpr | 1 when GDPR applies, 0 when it doesn't. Leave it out to let the ad server decide from the user's location. |
tcf | An IAB TCF v2 consent string. |
gpp, gpp_sid, us_privacy | US privacy signals (GPP and the older US Privacy string). |
ads | Explicit consent to personalized ads and device IDs. Without it, under GDPR, TCF purpose 1 decides. |
analytics | false runs analytics without a persistent ID (cookieless mode). |
Under GDPR the SDK sends no advertising ID unless ads is true or the TCF string allows it, and without analytics consent it stores nothing for analytics. For a "Reset advertising ID" button in your privacy panel, call SofAds.resetAdvertisingId(): it creates a new SofAds install ID (the TV's own advertising ID is reset in the TV's settings).
Consent screen
Apps without a consent tool of their own don't need to build one: the SDK has a consent screen for TVs. It shows once, right after init() (like the consent prompt of a mobile app at launch), when all of these are true:
- GDPR applies: the SofAds ad server places the TV in the EU, Iceland, Liechtenstein, Norway, the UK or Switzerland, or your app passed
gdpr: 1; - your app passed no consent of its own (no
consentininit, nosetConsent()); - the app isn't marked Made for children (those apps never use a device ID or personalized ads, so there is nothing to ask);
- the user hasn't answered in the last 12 months.
The screen is a dialog over your app, which stays visible, dimmed, behind it. Its title names your app with the name from your dashboard ("Your privacy in Snowstrike"); you don't pass anything for that, and renaming the app in the dashboard updates it. A small SofAds logo in the dialog's footer shows who your ad partner is. The screen is in the user's language and works with the remote. It has Accept and Reject, the same size and style, and Settings with two switches, both off: Personalized ads (the TV's advertising ID) and Measurement (a persistent app ID for usage analytics), then Save. A QR code links to the full privacy notice.
| Answer | What the SDK does |
|---|---|
| Accept | Sends the advertising ID and uses the install ID for analytics. |
| Reject | No advertising ID, analytics without a persistent ID (cookieless). Ads still play: they just aren't personalized. |
| Settings | Exactly what the user switched on. |
| BACK | Closes without an answer: no IDs for this session, asked again next time. |
init() doesn't wait for the user: it resolves as usual and the screen opens right after. Your app is paused around the screen (onPause / onResume, as for an ad). A show call made while the screen is open waits for the answer and doesn't lose time: its own timeout starts after the screen. Prefer to ask later, for example after your own intro? Use consentScreen: "first-ad": the screen then shows right before the first ad instead. Without an answer the screen closes by itself after 120 seconds (timeouts: { consentScreenMaxSeconds }).
Add a privacy item to your app's menu so users can change their answer:
const consent = await SofAds.showConsent(); // { ads, analytics, decided }
SofAds.getConsent(); // the consent in force, any time
SofAds.on("consent", (e) => console.log(e)); // { ads, analytics, via }showConsent() also works outside the GDPR countries and with consentScreen: false. While an ad is on screen it resolves at once with decided: false.
Your own consent tool (CMP): pass its result with init({ consent }) or SofAds.setConsent(), and set consentScreen: false so the SofAds screen never appears. The SofAds screen doesn't produce an IAB TCF string yet, so ad partners treat its answers as "no consent" and show contextual ads; SofAds' own ads use the answer directly.
The SDK counts the answers (accept, reject or the chosen settings) as one anonymous event without an install ID, so consent rates can be measured without tracking anyone.
Test mode
Until your store listing is live, your app gets test ads only: real ad screens, labeled "Test ad", never billed. A development build can ask for them at any time:
SofAds.init({ appId: "sof_YOUR_APP_ID", test: true });The SDK logs one console line explaining why it serves test ads (listing pending, in review, or a registered test device), and ShowResult.test is true for test ads. Everything about test ads, the scan test and test devices is in Test ads and test devices.
Debug overlay
SofAds.debug(true) shows a panel at the bottom left of the screen, above your app but never taking input: the SDK version, the install ID as text and as a QR code (to register the TV as a test device), the app and platform, the listing status, test mode and its reason, integration warnings with a link to the fix, and a link to these docs. SofAds.debug(false) removes it. You can call it any time, also before init.
SofAds.debug(true);SofAds.getInfo() returns the same information as an object, for your own logs.
Other calls
| Call | What it does |
|---|---|
SofAds.prefetch({ placement, type? }) | Fetches one backup ad for a placement and preloads its media. Every break still asks for a fresh ad first; the backup only shows when that request gets no answer in time. Resolves true when it has one, false while SofAds has backup ads turned off. |
SofAds.closeAd() | Closes a visible ad at once, for example when your app is suspended. |
SofAds.isShowing() | true while an ad overlay is visible. |
document.addEventListener("visibilitychange", () => {
if (document.hidden && SofAds.isShowing()) SofAds.closeAd();
});Never-throw guarantees
- Every public call catches its own errors. Ads off, network down or odd firmware: your app carries on.
- Every show call resolves within a fixed time with
shown,no_fill,errorortimeout. closealways followsshow, andonResumealways followsonPause.- While an ad is visible it captures the remote keys, so your app never sees them; BACK works on every ad screen.