# "Instant Games SDK v8.0: FBInstant.overlayViews"


See [Instant Games SDK v8.0](https://developers.facebook.com/documentation/games/sdk-reference/v8.0) for the SDK overview, changelog, and root `FBInstant` reference.

## FBInstant.overlayViews

This module is for managing the creation and lifecycle of Instant games overlay views

### createOverlayViewAsync()

Similar to `FBInstant.overlayViews.createOverlayView()` but returns a promise instead. Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the provided view's xml file.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `fullyQualifiedOverlayViewFilename` | `string` | The fully qualified name of the overlay view XML file (relative to the root of your game bundle) to be used as the layout. For example,                                        "overlay_views/profile_overlay.xml" given profile_overlay.xml is present in an 'overlay_views' folder in the root of your game bundle |
| `domElement` | `HTMLElement` | The HTMLElement to attach the iframe element to via the `appendChild` method. If you pass in `document.body`, we will perform `document.body.appendChild(overlayView.iframeElement)` for you |
| `iFrameStyle` | `string` _(optional)_ | The css inline style to apply to the iframe element |
| `pathToCSS` | `string` _(optional)_ | The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css" |
| `initialData` | `Object` _(optional)_ | The initial data to be passed to the view |

**Returns:** `Promise<`[`OverlayView`](#overlayview)`>` — A promise that resolves with the overlay view object if successful, otherwise rejects with an [`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror). Note that you would still have to call `showAsync()` on the overlay view in order to display it

**Example:**

```javascript
const overlayView = await FBInstant.overlayViews.createOverlayViewAsync(
 "overlay_views/profile_overlay.xml",
 document.body,
 "width: 100px; height: 100px;",
 "css/styles.css",
 {score: 30}
);
```

---

### createOverlayViewWithXMLStringAsync()

Similar to `createOverlayViewWithXMLString` but returns a promise instead. Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the string passed to this function

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `overlayViewContentOverride` | `string` | The String of the Overlay XML that is passed into Instant Game SDK |
| `domElement` | `HTMLElement` | The HTMLElement to attach the iframe element to via the `appendChild` method. If you pass in `document.body`, we will perform `document.body.appendChild(overlayView.iframeElement)` for you |
| `iFrameStyle` | `string` _(optional)_ | The css inline style to apply to the iframe element |
| `pathToCSS` | `string` _(optional)_ | The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css" |
| `initialData` | `Object` _(optional)_ | The initial data to be passed to the view |
| `pathToOverlayFiles` | `string` _(optional)_ | The String of the path that holds the overlay related files. For example, "ig_views" |

**Returns:** `Promise<`[`OverlayView`](#overlayview)`>` — A promise that resolves with the overlay view object if successful, otherwise rejects with an [`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror)

**Example:**

```javascript
const overlayView = await FBInstant.overlayViews.createOverlayViewWithXMLStringAsync(
 "<View></View>",
 document.body,
 "width: 100px; height: 100px;",
 "css/styles.css",
 {score: 30},
 "overlay_views",
);
```

---

### createOverlayView()

Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the provided view's xml file

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `fullyQualifiedOverlayViewFilename` | `string` | The fully qualified name of the overlay view XML file (relative to the root of your game bundle) to be used as the layout. For example,                                        "overlay_views/profile_overlay.xml" given profile_overlay.xml is present in an 'overlay_views' folder in the root of your game bundle |
| `pathToCSS` | `string` _(optional)_ | The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css" |
| `initialData` | `Object` _(optional)_ | The initial data to be passed to the view |
| `onInitializedSuccessCallback` | `function(`[`OverlayView`](#overlayview)`): void` _(optional)_ | The callback to be called when the view is successfully initialized and ready to be shown |
| `onInitializedErrorCallback` | `function(`[`OverlayView`](#overlayview)`, `[`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror)`): void` _(optional)_ | The callback to be called when an error occurs while initializing the view |

**Returns:** [`OverlayView`](#overlayview) — The created overlay view instance

**Example:**

```javascript
FBInstant.overlayViews.createOverlayView(
 "overlay_views/profile_overlay.xml",
 "css/styles.css",
 {score: 30},
 (overlayView) => console.log("overlay view created successfully"),
 (overlayView, error) => console.log("overlay view creation failed with error: ", error)
);
```

---

### createOverlayViewWithXMLString()

Creates an Instant Games overlay view that can be used to render user's information as defined by the layout specified in the string passed to this function

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `overlayViewContentOverride` | `string` | The String of the Overlay XML that is passed into Instant Game SDK |
| `pathToCSS` | `string` _(optional)_ | The String of the path that holds the file the Overlay View will use for styling. For example, "css/styles.css" |
| `initialData` | `Object` _(optional)_ | The initial data to be passed to the view |
| `onInitializedSuccessCallback` | `function(`[`OverlayView`](#overlayview)`): void` _(optional)_ | The callback to be called when the view is successfully initialized and ready to be shown |
| `onInitializedErrorCallback` | `function(`[`OverlayView`](#overlayview)`, `[`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror)`): void` _(optional)_ | The callback to be called when an error occurs while initializing the view |
| `pathToOverlayFiles` | `string` _(optional)_ | The String of the path that holds the overlay related files. For example, "ig_views" |

**Returns:** [`OverlayView`](#overlayview) — The created overlay view instance

**Example:**

```javascript
FBInstant.overlayViews.createOverlayViewWithXMLString(
  "<View></View>",
  "css/styles.css",
  {score: 30},
  (overlayView) => console.log("overlay view created successfully"),
  (overlayView, error) => console.log("overlay view creation failed with error: ", error),
  "overlay_views"
);
```

---

### createProfilePictureOverlayViewAsync()

Creates a profile picture overlay view that can be used to render the user's profile picture without requiring having to specify XML.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `domElement` | `HTMLElement` | The HTMLElement to attach the iframe element to via the `appendChild` method. If you pass in `document.body`, we will perform `document.body.appendChild(overlayView.iframeElement)` for you |
| `imageStyle` | `string` _(optional)_ | The css inline style to apply to the profile picture |
| `iFrameStyle` | `string` _(optional)_ | The css inline style to apply to the iframe element |

**Returns:** `Promise<`[`OverlayView`](#overlayview)`>` — A promise that resolves with the overlay view object if successful, otherwise rejects with an [`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror). Note that you would still have to call `showAsync()` on the overlay view in order to display it.

**Example:**

```javascript
const overlayView = await FBInstant.overlayViews.createProfilePictureOverlayViewAsync(
  document.body,
  "width: 100px; height: 100px;",
  "width: 100px; height: 100px;"
);
```

---

### createProfileNameOverlayViewAsync()

Creates a user profile name overlay view that can be used to render the user's first name without requiring having to specify XML.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `domElement` | `HTMLElement` | The HTMLElement to attach the iframe element to via the `appendChild` method. If you pass in `document.body`, we will perform `document.body.appendChild(overlayView.iframeElement)` for you |
| `textStyle` | `string` _(optional)_ | The css inline style to apply to the profile name text |
| `iFrameStyle` | `string` _(optional)_ | The css inline style to apply to the iframe element |
| `pathToCss` | `string` _(optional)_ | Optional path to CSS file for additional styling |

**Returns:** `Promise<`[`OverlayView`](#overlayview)`>` — A promise that resolves with the overlay view object if successful, otherwise rejects with an [`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror). Note that you would still have to call `showAsync()` on the overlay view in order to display it.

**Example:**

```javascript
const overlayView = await FBInstant.overlayViews.createProfileNameOverlayViewAsync(
  document.body,
  "width: 100px; height: 100px;",
  "width: 100px; height: 100px;"
);
```

---

### setCustomEventHandler()

Set a custom event handler for a callback string that is triggered from any of your overlay views.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `handler` | `function(string, string): void` | The callback to be called when this custom event  is triggered. The callback receives two parameters: - eventStr: A string containing the event data - overlayID: A string identifying which overlay triggered the event |

**Returns:** `void`

**Example:**

```javascript
FBInstant.overlayViews.setCustomEventHandler((eventStr, overlayID) => {
   document.getElementById('overlayCustomEventOutput').innerHTML +=
       ' |' + eventStr + ' triggered by ' + overlayID + '| ';
 });
```

---

### Image error handling with onErrorEvent

The `<Image>` XML component supports an `onErrorEvent` attribute that fires a custom event through the `setCustomEventHandler` callback when an image fails to load. This is useful for detecting broken profile photos or other image loading failures and responding gracefully in your game.

The `onErrorEvent` attribute accepts a string value that becomes the event name passed to your custom event handler. You can use template data binding in the event name to identify which image failed.

**Setting up the error handler:**

```javascript
await FBInstant.overlayViews.setCustomEventHandler((eventName, overlayID) => {
  if (eventName.startsWith('photo_load_failed_')) {
    const failedPlayerId = eventName.replace('photo_load_failed_', '');
    console.log(`Photo failed for player ${failedPlayerId} in overlay ${overlayID}`);
  }
});
```

**Using onErrorEvent in XML:**

```xml
<View>
  <Text content="{{FBInstant.player.name}}" />
  <Image
    src="{{FBInstant.player.photo}}"
    onErrorEvent="photo_load_failed_{{playerId}}"
    width="60"
  />
</View>
```

**Full example with inline XML:**

```javascript
await FBInstant.overlayViews.setCustomEventHandler((eventName, overlayID) => {
  if (eventName.startsWith('photo_load_failed_')) {
    const failedPlayerId = eventName.replace('photo_load_failed_', '');
    console.log(`Photo failed for player ${failedPlayerId} in overlay ${overlayID}`);
  }
});

const xml = `<View style="{{styleData}}">
  <Text content="Hello World! {{playerId}}" />
  <Text content="{{FBInstant.player.name}}" />
  <Image src="{{FBInstant.player.photo}}" onErrorEvent="photo_load_failed_{{playerId}}" width="60" />
</View>`;

const overlayView = await FBInstant.overlayViews.createOverlayViewWithXMLStringAsync(
  xml,
  document.body,
  "position:absolute; left:20px; top:20px; width:400px; height:400px;",
  "ig_views/styles.css",
  {
    playerId: '24768611972797445',
    styleData: 'border:4px solid red;',
  },
  "ig_views",
);
await overlayView.showAsync();
```

When the image at `src` fails to load, the overlay view fires the event name specified in `onErrorEvent` (with any template tokens resolved) to the handler registered via `setCustomEventHandler()`.

---

### getOverlayViews()

Returns a map of all the overlay views that have been created.

**Returns:** `Map<string, `[`OverlayView`](#overlayview)`>` — Returns a map of all the overlay views that have been created

---

## Types

### OverlayViewError

Represents an error that occured during the lifecycle of an overlay view.

**Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `caller` | `string` | Function that triggered the error (e.g. showAsync) |
| `error` | `mixed` | The specific error object that was thrown (e.g.   APIError) |

---

### OverlayView

Represents an Instant Games overlay view.

#### getID()

The unique ID that is associated with this overlay view.

**Returns:** `string` — The unique identifier for this overlay view

---

#### getIFrameElement()

The iframe element for this overlay view that you can freely attach and position in your DOM tree.

**Returns:** `HTMLIFrameElement` — The iframe element for this overlay view

---

#### getStatus()

Status of the overlay view.

**Returns:** `ShieldOverlayLifecycleState` — The current lifecycle state of the overlay view

---

#### getInitialData()

Initial data that was passed in to this overlay view on creation.

**Returns:** `?Object` — The initial data passed to this overlay view, or null if none was provided

---

#### getErrors()

List of errors that occurred during the lifecycle of this overlay view.

**Returns:** `Array<`[`OverlayViewError`](#overlayviewerror)`>` — Array of errors that occurred during the lifecycle of this overlay view

---

#### showAsync()

Call this method to show the overlay view after you attach it to your DOM tree.

**Returns:** `Promise<mixed>` — A promise that resolves when the overlay view is shown

---

#### updateAsync()

Call this method to update the overlay view with new data. You still need to call `showAsync()` on the overlay view in order to display the new data.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `updatedData` | `Object` | The data to be passed to the overlay view |

**Returns:** `Promise<void>` — A promise that resolves when the update is complete, otherwise rejects with an [`APIError`](https://developers.facebook.com/documentation/games/sdk-reference/v8.0#apierror). Note that you would still have to call `showAsync()` on the overlay view in order to display it

---

#### dismissAsync()

Call this method to hide the overlay view.

**Returns:** `Promise<void>` — A promise that resolves when the overlay view is hidden

---