# Event Listeners

### 소개

위젯에서 App으로 데이터를 보낼때 동작 하는 함수들 입니다.

<table><thead><tr><th width="220">이름</th><th>설명</th></tr></thead><tbody><tr><td>onMessage</td><td>위젯에서 App으로 보낸 메시지를 수신 할 때 동작하는 함수입니다.</td></tr></tbody></table>

## 📚 API 설명 및 예제

### onMessage

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

위젯에서 App으로 메시지를 보내면 callback 함수가 동작합니다.

**파라미터**

<table><thead><tr><th width="133.33333333333331">이름</th><th width="138">타입</th><th>설명</th></tr></thead><tbody><tr><td>player</td><td>Player</td><td>player는 위젯을 소유한 플레이어를 가르킴<br>player 파라미터의 이름은 임의로 변경 가능</td></tr><tr><td>data</td><td>Object</td><td>data는 위젯에서 App으로 보낸 메시지를 가르킴<br>data 파라미터의 이름은 임의로 변경 가능</td></tr></tbody></table>

**예제**

x 버튼을 눌러서 위젯창 닫는 기능 만들어보기

{% file src="/files/PizN4kVrM1Ip04mOk3Pi" %}

![](/files/87baqyEmWiYLkLDHnQUa)

```jsx
// 플레이어가 입장할 때 동작하는 함수
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) {
		// 위젯에서 App으로 'type: close'라는 메시지를 보내면 위젯을 파괴함
		if (msg.type == "close") {
			player.showCenterLabel("위젯이 닫혔습니다.");
			player.tag.widget.destroy();
			player.tag.widget = null;
		}
	});
});
```

**sample.html**: 버튼과 스크립트 부분

```jsx
<i onclick="closeWidget()" class="fa-solid fa-xmark"></i>
<script type="text/javascript">
	// x 버튼을 누르면 호출되는 함수
	function closeWidget() {
		// App으로 메시지를 보냄.
		window.parent.postMessage(
			{
				type: "close",
			},
			"*"
		);
	}
</script>
```

### 부록

[위젯에서 사용가능한 문법](/creator/reference/scriptaction.md)


---

# 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://docs-kr.zep.us/zep-script-api/zepscriptapi/scriptwidget/event-listeners.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.
