# Event Listeners

### Introduction

Provided below are functions that activate when data is sent to the App from the widget.

<table><thead><tr><th width="190">Name</th><th>Description</th></tr></thead><tbody><tr><td>onMessage</td><td>Function that activates when messages sent from widget are received on the App</td></tr></tbody></table>

## 📚 API Explanation and Example

### onMessage

{% hint style="info" %}
widget.onMessage.Add(function(player, data: any){});
{% endhint %}

Callback function that activates when a message is sent from the widget to the App.

**Parameters**

<table><thead><tr><th width="122.33333333333331">Name</th><th width="116">Type</th><th>Description</th></tr></thead><tbody><tr><td>player</td><td>Player</td><td>The player who owns the widget</td></tr><tr><td>data</td><td>Object</td><td>The message sent from the widget to the App</td></tr></tbody></table>

**Example**

Create a function to close the widget screen when x is pressed.

{% file src="<https://3059601135-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MkvEvcz_LX5eDyvl13E%2Fuploads%2FjlwvD7Qia1a1hh32b2tY%2Fsample_EventListener.zip?alt=media&token=ccde59f6-4d24-48d4-bc86-d613ed677517>" %}

<div align="left"><figure><img src="https://3059601135-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MkvEvcz_LX5eDyvl13E%2Fuploads%2F4WzjhpaKxogqkjQPMSlY%2FUntitled.png?alt=media&#x26;token=e69b5ead-7fcd-4a67-8732-5dad9dc26cd9" alt=""><figcaption></figcaption></figure></div>

```jsx
// Activates function when a player enters
App.onJoinPlayer.Add(function (player) {
	player.tag = {
		widget: null,
	};

	player.tag.widget = player.showWidget("sample.html.html", "top", 600, 500);
	player.tag.widget.onMessage.Add(function (player, msg) {
		// Closes the widget when the 'type: close' message is sent from the widget to the App 
		if (msg.type == "close") {
			player.showCenterLabel("Widget has been closed.");
			player.tag.widget.destroy();
			player.tag.widget = null;
		}
	});
});
```

**sample.html**: Button and script section

```jsx
<i onclick="closeWidget()" class="fa-solid fa-xmark"></i>
<script type="text/javascript">
			// Calls the function when x button is pressed
			function closeWidget() {
				// Sends message to App 
				window.parent.postMessage(
					{
						type: "close",
					},
					"*"
				);
			}
</script>
```
