> 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 guides you on how to detect and control the main events that occur while the app is running. For example, **Back button event**and **App entry completion event**can be handled.

### 1. Detecting back button events

Controlling the back button event can prevent users from accidentally closing a page. For example, while making a payment or filling out a form, you can block the screen from closing when the back button is pressed.

**Key features**

| Feature                                               | Description                                                                 |
| ----------------------------------------------------- | --------------------------------------------------------------------------- |
| `backEvent`                                           | An event that occurs when the back button is pressed.                       |
| `graniteEvent.addEventListener('backEvent', { ... })` | Subscribe 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 a confirmation dialog when the user presses back, and allows navigation when “Confirm” is pressed.

{% 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're editing will not be saved. Do you want to leave?');
    if (shouldLeave) {
      // Write the code to exit.
    }
  },
  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're editing will not be saved. Do you want to leave?');
        if (shouldLeave) {
          // Write the code to exit.
        }
      },
      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 text 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.

**Key features**

| Feature                                               | Description                                           |
| ----------------------------------------------------- | ----------------------------------------------------- |
| `homeEvent`                                           | An event that occurs when the home button is pressed. |
| `graniteEvent.addEventListener('homeEvent', { ... })` | (Web) Subscribe to the event.                         |
| `homeEvent.subscribe(callback)`                       | (React Native) Subscribe 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 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`detects native events (such as back navigation), `appsInTossEvent`detects changes in the Toss app's internal state.
* Registered event listeners must always **be cleaned up when the component unmounts**.
* When executing event-based work, be sure to add **an error handler (onError)** to prepare for exceptions.


---

# 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.
