> For the complete documentation index, see [llms.txt](https://wiki.playgama.com/playgama-ad/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.playgama.com/playgama-ad/integration/standalone-sdk.md).

# Standalone SDK

{% hint style="warning" %}
**v0.2** is still supported, but new integrations should use **v0.3**. See the version tabs below for the differences.
{% endhint %}

## Overview

Playgama Ad provides a monetization solution for web games and gaming platforms. The solution supports the following ad formats:

* Interstitial ads
* Rewarded ads
* Display ads (banners)

<mark style="background-color:purple;">**Access**</mark>

**Playgama Ad** is currently available in **open beta**, please contact us using the Contact Us form at [**https://playgama.com/adv**](https://playgama.com/adv).

## Installation

Add the SDK script in your HTML `head`. Pick the tab for the SDK version you're integrating:

{% tabs %}
{% tab title="v0.3" %}

```html
<script src="https://playgama.com/ads/v0.3.js?clid=<clid>"></script>
```

Replace `<clid>` with your Client ID. It is passed as the `clid` query parameter on the script URL itself.

### Config ID

To use a different ad configuration than the one linked to your `clid`, pass its ID via the `config_id` query parameter:

```html
<script src="https://playgama.com/ads/v0.3.js?clid=<clid>&config_id=<your-config-id>"></script>
```

{% endtab %}

{% tab title="v0.2" %}

```html
<script src="https://playgama.com/ads/<partner_name_sdk>.v0.2.js"></script>
```

The SDK build is provided by your account manager. Replace `<partner_name_sdk>` with the name provided for your account, and use only the SDK build assigned to your account.

### Country Code

The SDK needs to know the user's country. By default it makes a network request to resolve it. If you already know the country on your side, you can pass it via the `data-country-code` attribute on the script tag, and the SDK will use it directly and skip the request:

```html
<script src="https://playgama.com/ads/<partner_name_sdk>.v0.2.js" data-country-code="DE"></script>
```

The value must be a two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code.
{% endtab %}
{% endtabs %}

Your `clid` is the `playgama_clid` assigned to your account.

### Asynchronous Initialization

If you load the SDK asynchronously (or you are not sure when it loads), use `pgAdsCallbacks` to ensure the SDK is ready before you use it:

{% tabs %}
{% tab title="v0.3" %}

```javascript
window.pgAdsCallbacks = window.pgAdsCallbacks || [];
window.pgAdsCallbacks.push(async () => {
  await window.pgAds.init();
});
```

{% endtab %}

{% tab title="v0.2" %}

```javascript
window.pgAdsCallbacks = window.pgAdsCallbacks || [];
window.pgAdsCallbacks.push(async () => {
  await window.pgAds.init({ clid: "<your-clid>" });
});
```

{% endtab %}
{% endtabs %}

## Quick Start

Below is the minimal setup to initialize the SDK and display an interstitial ad:

{% tabs %}
{% tab title="v0.3" %}

```javascript
// 1. Initialize the SDK (clid comes from the script URL, see Installation)
await window.pgAds.init();

// 2. Request an Interstitial Ad
const banner = await window.pgAds.requestOutOfPageAd("interstitial");

// 3. Show the Ad when ready
banner.addEventListener("ready", () => {
  banner.show();
});
```

{% endtab %}

{% tab title="v0.2" %}

```javascript
// 1. Initialize the SDK
await window.pgAds.init({ clid: "<your-clid>" });

// 2. Request an Interstitial Ad
const banner = await window.pgAds.requestOutOfPageAd("interstitial");

// 3. Show the Ad when ready
banner.addEventListener("ready", () => {
  banner.show();
});
```

{% endtab %}
{% endtabs %}

## API Reference

The SDK exposes the global `window.pgAds` object with the following methods:

### 1. `init`

Initializes the ads service. This must be called before requesting any ads.

{% tabs %}
{% tab title="v0.3" %}

```
init(options?): Promise<void>
```

* **Parameters**:
  * `options` (object, optional):
    * `gameId` (string, optional): Identifier for the current game.

```javascript
await window.pgAds.init({ gameId: "<game-identifier>" });
```

{% endtab %}

{% tab title="v0.2" %}

```
init(options): Promise<void>
```

* **Parameters**:
  * `options` (object):
    * `clid` (string, required): Your unique Client ID.
    * `gameId` (string, optional): Identifier for the current game.

```javascript
await window.pgAds.init({ clid: "<your-clid>", gameId: "<game-identifier>" });
```

{% endtab %}
{% endtabs %}

### 2. `setGameId(gameId): void`

Updates the game identifier after initialization. Use this when navigating between games without reinitializing the SDK.

* **Parameters**:
  * `gameId` (string | undefined): Identifier for the current game, or `undefined` to clear it.

```javascript
window.pgAds.setGameId("<game-identifier>");
```

### 3. `requestOutOfPageAd(type): Promise<PublicOutOfPageAdBanner>`

Requests a full-screen or overlay ad (Interstitial or Rewarded).

* **Parameters**:
  * `type` (string): The ad format.
    * `'interstitial_preroll'`: Full-screen ad before content.
    * `'interstitial'`: Full-screen ad between content (e.g. at natural breaks in gameplay).
    * `'rewarded'`: Opt-in full-screen ad that rewards the user.

```javascript
const rewardedBanner = await window.pgAds.requestOutOfPageAd("rewarded");
```

### 4. `requestPageAd(options): Promise<PublicPageAdBanner>`

Requests a standard display banner to be rendered inside a specific DOM element.

* **Parameters**:
  * `options` (object):
    * `el` (string): ID of the DOM element to render the ad in.
    * `type` (string): The ad type (e.g., `'banner_1'`, `'banner_2'`). Contact support to get your personal banner types.
    * `sizes` (array): Array of sizes e.g. `[[300, 250], [300, 300], 'fluid']`. Contact support to get all available sizes.
    * `refresh` (number, optional): Auto-refresh interval in seconds.

```javascript
const banner = await window.pgAds.requestPageAd({
  el: "ad-container-id",
  type: "banner_1",
  sizes: [[300, 300]],
});
```

### 5. `requestVideoPageAd(options): Promise<PublicPageVideoAdBanner>`

Requests an in-page video banner to be rendered inside a specific DOM element.

Unlike `requestPageAd`, this method takes no `sizes` and no `refresh`: the creative is stretched to fill the element you point at, and it is not auto-refreshed.

* **Parameters**:
  * `options` (object):
    * `el` (string): ID of the DOM element to render the ad in. It must have a fixed width and height, since the SDK renders the creative into it. A collapsed element leaves nothing to fill.
    * `type` (string): The ad type (e.g. `'video_banner'`). Contact support to get your personal video banner types.

```javascript
const banner = await window.pgAds.requestVideoPageAd({
  el: "ad-video-container-id",
  type: "video_banner",
});
```

The returned object is a `PublicPageVideoAdBanner`, with the states and events:

| Event      | Description                                                |
| ---------- | ---------------------------------------------------------- |
| `rendered` | The ad has been rendered into your element                 |
| `viewable` | The ad became visible in the viewport.                     |
| `empty`    | No ad was rendered.                                        |
| `closed`   | The ad finished or was closed. The banner destroys itself. |

```javascript
banner.addEventListener("rendered", () => {
  // The video ad is on screen
});

banner.addEventListener("viewable", () => {
  // The video playing
});

banner.addEventListener("empty", (event) => {
  // no ad
});

banner.addEventListener("closed", () => {
  // The video finished or was closed
});
```

### 6. `preload(): Promise<void>`

Preloads ad provider scripts into the browser cache.

> **When to use:** This method is only needed if you have a **same-origin iframe** on your page inside which the SDK will be initialized (e.g. a game iframe hosted on the same domain). In that case, call `preload()` on the **parent page** before adding the iframe to the DOM, so the scripts are already cached when the SDK initializes inside the iframe.
>
> **If you don't have such an iframe**, skip `preload()` entirely and call `init()` directly.
>
> **Note:** Due to browser cache partitioning, this optimization does **not** work with cross-origin iframes: resources fetched in the parent are not reused in iframes on a different domain.

```javascript
// Only if you have a same-origin game iframe:
// Call as early as possible, before adding the iframe to the page
window.pgAds.preload();
```

## Banner Lifecycle

All ad objects returned by requests (`PublicPageAdBanner`, `PublicPageVideoAdBanner`, and `PublicOutOfPageAdBanner`) share a common lifecycle managed through **states** and **events**.

### Banner States

Check `banner.state` (string) to determine the current status of an ad:

* `'loading'`: The ad is currently being fetched.
* `'ready'`: The ad has loaded and is ready to be shown.
* `'showing'`: The ad is currently visible to the user.
* `'empty'`: No ad fill was received.
* `'closed'`: The ad was closed or finished.

### Event Handling

Use `banner.addEventListener(event, callback)` to react to lifecycle changes.

#### Common Events

| Event      | Description                                                      |
| ---------- | ---------------------------------------------------------------- |
| `ready`    | Fired when `state` becomes `'ready'`. You can now call `show()`. |
| `empty`    | Fired when no ad is available (`state` becomes `'empty'`).       |
| `rendered` | Fired when the ad is physically rendered in the DOM.             |
| `viewable` | Fired when the ad becomes visible in the viewport.               |

#### Specific Events

| Event      | Description                                                                                    |
| ---------- | ---------------------------------------------------------------------------------------------- |
| `rewarded` | **(Rewarded Ads only)** Fired when the user completes the video. Grant the reward here.        |
| `closed`   | Fired when the user closes the ad or it finishes automatically. Resume your game/content here. |

## Ad Objects

### `PublicOutOfPageAdBanner`

Returned by `requestOutOfPageAd()`. Represents high-impact, overlay ads.

#### Methods

* **`show(): void`**
  * Displays the ad. Throws an error if the ad is not in the `'ready'` state.

#### Example: Rewarded Ad Flow

```javascript
const banner = await window.pgAds.requestOutOfPageAd("rewarded");

banner.addEventListener("ready", () => {
  banner.show();
});

banner.addEventListener("rewarded", () => {
  // User watched the video
  grantUserReward();
});

banner.addEventListener("closed", () => {
  // Ad closed, resume game loop
  resumeGame();
});

banner.addEventListener("empty", () => {
  // No ad available
  console.log("No fill");
});
```

### `PublicPageAdBanner`

Returned by `requestPageAd()`. Represents standard in-page display ads.

* These ads are typically rendered automatically into the container provided in `el`.
* You mostly listen to `empty` or `rendered` events for layout adjustments.
