# Display Library API Reference

This page documents the `n360ortbDisplay` library, which handles rendering display ads from n360ortb bids. It is loaded inside GAM creatives and handles iframe, SafeFrame, and cross-domain rendering contexts automatically.

## Script URL

```html
<script src="https://lib.nexx360.io/nexx360display/api.js"></script>
```

This script exposes the `window.n360ortbDisplay` object.

## SafeFrame Compatibility

The library works both **with and without SafeFrame**. The same creative code runs in all GAM rendering contexts — the library detects the environment at runtime and adapts automatically:

| Context                                       | How it works                                                                                               |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| **Without SafeFrame** (friendly iframe)       | Accesses the parent `n360ortb` API directly to retrieve ad markup, resizes the iframe via `frameElement`   |
| **With SafeFrame** (cross-origin iframe)      | Uses `postMessage` to request ad data from the parent page, then sends a resize request back to the parent |
| **Cross-domain** (other cross-origin iframes) | Same postMessage mechanism as SafeFrame, using the `__n360_locator__` frame to find the parent listener    |

No configuration change or different creative template is needed — one template handles all cases.

***

## Methods Overview

| Method                                                | Description                                     |
| ----------------------------------------------------- | ----------------------------------------------- |
| [renderAd()](#renderad)                               | Main render function - auto-detects environment |
| [renderMarkup()](#rendermarkup)                       | Render ad markup with a size string             |
| [renderMarkupWithSize()](#rendermarkupwithsize)       | Render ad markup with explicit dimensions       |
| [enableCreativeMessaging()](#enablecreativemessaging) | Enable parent-side message listener             |
| [init()](#init)                                       | Initialize the library (optional)               |
| [debug()](#debug)                                     | Enable or disable debug mode                    |
| [parseSize()](#parsesize)                             | Parse a size string into width/height           |
| [detectEnvironment()](#detectenvironment)             | Detect the current rendering environment        |

***

## renderAd()

Main rendering function used in GAM creatives. Automatically detects whether the creative is running in a friendly iframe, SafeFrame, or cross-origin iframe and uses the appropriate rendering strategy.

### Syntax

```javascript
n360ortbDisplay.renderAd(doc, config)
```

### Parameters

| Parameter | Type           | Description                                      |
| --------- | -------------- | ------------------------------------------------ |
| doc       | `Document`     | The document to render into (usually `document`) |
| config    | `RenderConfig` | Render configuration object                      |

#### RenderConfig

| Property     | Required | Type                        | Description                                         |
| ------------ | -------- | --------------------------- | --------------------------------------------------- |
| bidId        | Yes\*    | string                      | Bid ID from GAM targeting (`n360_bid`)              |
| size         | No       | string                      | Size string (e.g., `'300x250'`)                     |
| width        | No       | number                      | Width in pixels (alternative to `size`)             |
| height       | No       | number                      | Height in pixels (alternative to `size`)            |
| adm          | No       | string                      | Direct ad markup - if provided, renders immediately |
| pubUrl       | No       | string                      | Publisher URL for postMessage origin validation     |
| cacheHost    | No       | string                      | Cache server host                                   |
| cacheUrl     | No       | string                      | Cache endpoint path                                 |
| uuid         | No       | string                      | Cache UUID                                          |
| clickThrough | No       | string                      | Click-through URL                                   |
| debug        | No       | boolean \| number \| string | Enable debug logging (`1`, `true`, or `'1'`)        |

\*Either `bidId` or `adm` is required.

### Returns

`Promise<boolean>` - Resolves to `true` if rendering succeeded.

### Rendering Environments

`renderAd()` automatically detects the context and adapts:

| Environment      | Detection                        | Behavior                                                       |
| ---------------- | -------------------------------- | -------------------------------------------------------------- |
| **Direct**       | Parent window has `n360ortb` API | Retrieves ad markup directly from the bid store                |
| **SafeFrame**    | `window.$sf.ext` is present      | Uses postMessage to request ad data, then renders              |
| **Cross-domain** | Default fallback                 | Uses postMessage via `__n360_locator__` frame to fetch ad data |

### Example

```html
<script src="https://lib.nexx360.io/nexx360display/api.js"></script>
<script>
  var ucTagData = {
    bidId: '%%PATTERN:n360_bid%%',
    size: '%%PATTERN:n360_sz%%',
    pubUrl: '%%SITE%%'
  };
  n360ortbDisplay.renderAd(document, ucTagData);
</script>
```

***

## renderMarkup()

Renders ad markup directly into the document using a size string. Useful for standalone rendering when you already have the ad markup.

### Syntax

```javascript
n360ortbDisplay.renderMarkup(doc, adm, size, container)
```

### Parameters

| Parameter | Required | Type          | Description                                           |
| --------- | -------- | ------------- | ----------------------------------------------------- |
| doc       | Yes      | `Document`    | The document to render into                           |
| adm       | Yes      | string        | Ad markup (HTML/JavaScript)                           |
| size      | Yes      | string        | Size string (e.g., `'300x250'`)                       |
| container | No       | `HTMLElement` | Target container element. Defaults to `document.body` |

### Returns

`boolean` - `true` if rendering succeeded.

### Example

```javascript
var adMarkup = '<div>Ad content here</div>';
n360ortbDisplay.renderMarkup(document, adMarkup, '300x250');

// With a specific container
var container = document.getElementById('ad-slot');
n360ortbDisplay.renderMarkup(document, adMarkup, '300x250', container);
```

***

## renderMarkupWithSize()

Same as `renderMarkup()` but accepts width and height as separate numbers instead of a size string.

### Syntax

```javascript
n360ortbDisplay.renderMarkupWithSize(doc, adm, width, height, container)
```

### Parameters

| Parameter | Required | Type          | Description                                           |
| --------- | -------- | ------------- | ----------------------------------------------------- |
| doc       | Yes      | `Document`    | The document to render into                           |
| adm       | Yes      | string        | Ad markup (HTML/JavaScript)                           |
| width     | Yes      | number        | Width in pixels                                       |
| height    | Yes      | number        | Height in pixels                                      |
| container | No       | `HTMLElement` | Target container element. Defaults to `document.body` |

### Returns

`boolean` - `true` if rendering succeeded.

### Example

```javascript
var adMarkup = '<div>Ad content here</div>';
n360ortbDisplay.renderMarkupWithSize(document, adMarkup, 300, 250);
```

***

## enableCreativeMessaging()

Enables parent-side message listener for cross-domain and SafeFrame rendering. When a creative running inside a GAM iframe sends a postMessage requesting ad data, this listener responds with the bid markup.

{% hint style="info" %}
When using the n360ortb main library, creative messaging is set up automatically during `init()`. You only need to call `enableCreativeMessaging()` if you are **not** using n360ortb on the publisher page.
{% endhint %}

### Syntax

```javascript
var cleanup = n360ortbDisplay.enableCreativeMessaging(getBid)
```

### Parameters

| Parameter | Type                                                            | Description                                           |
| --------- | --------------------------------------------------------------- | ----------------------------------------------------- |
| getBid    | `(bidId: string) => { adm: string, size: string } \| undefined` | Function that returns the bid data for a given bid ID |

### Returns

`() => void` - A cleanup function that removes the message listener.

### Example

```javascript
// Set up messaging with a custom bid store
var cleanup = n360ortbDisplay.enableCreativeMessaging(function(bidId) {
  return myBidStore.find(function(b) {
    return b.bidId === bidId;
  });
});

// Later, to remove the listener:
cleanup();
```

***

## init()

Initializes the library. This is optional and only needed to enable debug mode at startup.

### Syntax

```javascript
n360ortbDisplay.init(options)
```

### Parameters

| Parameter     | Type    | Description          |
| ------------- | ------- | -------------------- |
| options.debug | boolean | Enable debug logging |

### Example

```javascript
n360ortbDisplay.init({ debug: true });
```

***

## debug()

Enables or disables debug mode. When enabled, detailed logs are printed to the browser console with module-specific prefixes.

### Syntax

```javascript
n360ortbDisplay.debug(enabled)
```

### Parameters

| Parameter | Type    | Description                          |
| --------- | ------- | ------------------------------------ |
| enabled   | boolean | `true` to enable, `false` to disable |

### Debug Log Prefixes

| Prefix                         | Module                           |
| ------------------------------ | -------------------------------- |
| `[n360ortb-display]`           | General                          |
| `[n360ortb-display:env]`       | Environment detection            |
| `[n360ortb-display:messenger]` | PostMessage communication        |
| `[n360ortb-display:parent]`    | Parent-side listener             |
| `[n360ortb-display:dom]`       | DOM operations and iframe resize |
| `[n360ortb-display:safeframe]` | SafeFrame/cross-domain rendering |
| `[n360ortb-display:iframe]`    | Direct iframe rendering          |

### Example

```javascript
// Enable debug via method
n360ortbDisplay.debug(true);

// Or via renderAd config
n360ortbDisplay.renderAd(document, {
  bidId: 'abc123',
  size: '300x250',
  debug: 1
});
```

***

## parseSize()

Parses a size string (e.g., `'300x250'`) into a width/height object.

### Syntax

```javascript
n360ortbDisplay.parseSize(size)
```

### Parameters

| Parameter | Type   | Description                          |
| --------- | ------ | ------------------------------------ |
| size      | string | Size string in `WIDTHxHEIGHT` format |

### Returns

`{ width: number, height: number } | null` - Parsed dimensions, or `null` if invalid.

### Example

```javascript
n360ortbDisplay.parseSize('300x250');
// { width: 300, height: 250 }

n360ortbDisplay.parseSize('invalid');
// null
```

***

## detectEnvironment()

Detects the current rendering environment.

### Syntax

```javascript
n360ortbDisplay.detectEnvironment()
```

### Returns

`'direct' | 'safeframe' | 'crossdomain'`

| Value           | Meaning                                                               |
| --------------- | --------------------------------------------------------------------- |
| `'direct'`      | Running in a friendly iframe with access to the parent `n360ortb` API |
| `'safeframe'`   | Running inside a GPT SafeFrame (`window.$sf.ext` is available)        |
| `'crossdomain'` | Running in a cross-origin iframe (default fallback)                   |

***

## VERSION

The current library version string.

```javascript
console.log(n360ortbDisplay.VERSION);
// e.g., "1.2.0"
```

***

## SafeFrame Resize Mechanism

GAM SafeFrames are cross-origin iframes that cannot be directly resized from inside the creative. The library handles this automatically using a parent-side resize pattern:

1. The creative renders the ad markup inside its iframe
2. The creative sends an `n360:resizeRequest` postMessage to the parent page
3. The n360ortb library on the parent page receives the request
4. The parent locates the SafeFrame via `googletag.pubads().getSlots()` and the `n360_bid` targeting key
5. The parent resizes both the iframe and its wrapper div (GAM creates a 1x1 wrapper that also needs resizing)

This happens transparently when using `renderAd()`. No additional setup is required.

## Next Steps

* [GAM Creative Setup](/integration-methods/direct-integration-n360ortb/gam-integration/gam-creative-setup.md) - Creative template used in GAM
* [API Reference](/integration-methods/direct-integration-n360ortb/api-reference.md) - n360ortb main library API
* [Standalone Integration](/integration-methods/direct-integration-n360ortb/standalone-integration.md) - Using renderMarkup() directly


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.nexx360.io/integration-methods/direct-integration-n360ortb/display-api-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
