> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-en/common/screen/event.md).

# Control Events

This document explains how to detect and control the main events that occur while the app is running. Representative examples include **back button event**and **app entry completion event**can be handled.

### 1. Detecting back button events

By controlling the back button event, you can prevent users from accidentally closing the page. For example, while making a payment or filling out a form, you can stop the screen from closing when they press Back.

**Main features**

| Feature                                               | Description                                                                 |
| ----------------------------------------------------- | --------------------------------------------------------------------------- |
| `backEvent`                                           | This is the event that occurs when the Back button is pressed.              |
| `graniteEvent.addEventListener('backEvent', { ... })` | Subscribes to the event.                                                    |
| `onEvent`                                             | Called when the Back button is pressed. The default back action is blocked. |
| `onError`                                             | Called when an error occurs while handling the event.                       |
| `unsubscription()`                                    | You can remove the registered event listener.                               |

In React Native, `useBackEvent()` you can implement the same logic with a hook.

**Example**

The example below shows displaying a confirmation dialog when the user presses Back, and allowing navigation if they press “Confirm.”

{% tabs %}
{% tab title="js" %}

```js
import { graniteEvent } from '@apps-in-toss/web-framework';

const unsubscription = graniteEvent.addEventListener('backEvent', {
  onEvent: () => {
    const shouldLeave = window.confirm('The content you are editing won't be saved. Do you want to leave?');
    if (shouldLeave) {
      // Write the code for leaving.
    }
  },
  onError: (error) => {
    console.error(`An error occurred: ${error}`);
  },
});

window.addEventListener('pagehide', () => {
  unsubscription();
});
```

{% endtab %}

{% tab title="React" %}

```tsx
import { graniteEvent } from '@apps-in-toss/web-framework';
import { useEffect, useState } from 'react';

function ConfirmBackNavigation() {
  const [formValue, setFormValue] = useState('');

  useEffect(() => {
    const unsubscription = graniteEvent.addEventListener('backEvent', {
      onEvent: () => {
        const shouldLeave = window.confirm('The content you are editing won't be saved. Do you want to leave?');
        if (shouldLeave) {
          // Write the code for leaving.
        }
      },
      onError: (error) => {
        alert(`An error occurred: ${error}`);
      },
    });

    return unsubscription;
  }, []);

  return (
    <div>
      <h2>Input form</h2>
      <textarea
        value={formValue}
        onChange={(e) => setFormValue(e.target.value)}
        placeholder="Please enter your content here"
        rows={5}
        style={{ width: '100%' }}
      />

  );
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { useEffect, useState } from 'react';
import { Alert, Button, View } from 'react-native';
import { useBackEvent } from '@granite-js/react-native';

function UseBackEventExample() {
  const backEvent = useBackEvent();

  const [handler, setHandler] = useState<{ callback: () => void } | undefined>(undefined);

  useEffect(() => {
    const callback = handler?.callback;

    if (callback != null) {
      backEvent.addEventListener(callback);

      return () => {
        backEvent.removeEventListener(callback);
      };
    }

    return;
  }, [backEvent, handler]);

  return (
    <View>
      <Button
        title="Add BackEvent"
        onPress={() => {
          setHandler({ callback: () => Alert.alert('back') });
        }}
      />
      <Button
        title="Remove BackEvent"
        onPress={() => {
          setHandler(undefined);
        }}
      />
    </View>
  );
}
```

{% endtab %}
{% endtabs %}

***

### 2. Controlling home button events

You can perform the necessary actions when the user presses the Home button.

**Main features**

| Feature                                               | Description                                                    |
| ----------------------------------------------------- | -------------------------------------------------------------- |
| `homeEvent`                                           | This is the event that occurs when the Home button is pressed. |
| `graniteEvent.addEventListener('homeEvent', { ... })` | (Web) Subscribes to the event.                                 |
| `homeEvent.subscribe(callback)`                       | (React Native) Subscribes to the event.                        |
| `onEvent`                                             | Called when the Home button is pressed.                        |
| `onError`                                             | Called when an error occurs while handling the event.          |
| `unsubscribe()`                                       | You can remove the registered event listener.                  |

In React Native, `homeEvent.subscribe()`You can implement the same logic using

**Example**

{% tabs %}
{% tab title="js" %}

```js
import { graniteEvent } from '@apps-in-toss/web-framework';

const unsubscribe = graniteEvent.addEventListener('homeEvent', {
  onEvent: () => {
    console.log('Home button clicked');
  },
});

unsubscribe(); // Remove the handler
```

{% endtab %}

{% tab title="React" %}

```tsx
import { graniteEvent } from '@apps-in-toss/web-framework';

const unsubscribe = graniteEvent.addEventListener('homeEvent', {
  onEvent: () => {
    window.alert('Home button clicked');
  },
});
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { homeEvent } from '@apps-in-toss/framework';

const unsubscribe = homeEvent.subscribe(() => {
  console.log('Home button clicked');
});

unsubscribe();
```

{% endtab %}
{% endtabs %}

***

### Notes

* `graniteEvent`handles native events (such as Back), `appsInTossEvent`detects changes in the Toss app's internal state.
* Registered event listeners must **be cleaned up when the component unmounts**.
* For tasks executed based on events, be sure to **an error handler (onError)** to prepare for exceptional situations.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-en/common/screen/event.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
