> For the complete documentation index, see [llms.txt](https://onestore-dev.gitbook.io/dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://onestore-dev.gitbook.io/dev/eng/tools/web-sdk/lifecycle.md).

# 03. Lifecycle Management

#### **SDK Load Sequence: from createSDK to startGameAsync**

The game must follow the sequence below. Violating the order raises an `sdk_not_initialized` error.

1. `createSDK()` : Obtain the SDK singleton
2. `initializeAsync()` : Initialize. Handshake with the app and receive game and environment information
3. `setLoadingProgress(n)` : Report game resource loading progress (0 to 100, called repeatedly)
4. `startGameAsync()` : Declare loading complete. The app removes the loading screen and shows the game

```javascript
import { createSDK } from "https://h5sdk.onestore.net/lib/{{version}}/onestore-h5-sdk.min.js";

var sdk = createSDK();

// Register listeners before initializeAsync() (see 'Event Listeners' below)
sdk.on("pause",  onPause);
sdk.on("resume", onResume);
sdk.on("exit",   onExit);

sdk.initializeAsync()
  .then(function (info) {
    if (info.err) {
       // Unsupported environment — notify the user of the initialization failure and exit
       return;
    }
    applyEnvironment(info);          // apply locale · ringerSilent · safeArea
    startLoading();
  })
  .catch(function (e) {
    // Initialization failed (no response from the app, etc.)
    console.error("initializeAsync failed", e.reason, e.message);
  });

function startLoading() {
  var timer = setInterval(function () {
    var progress = loadResources();  // 0 ~ 100
    sdk.setLoadingProgress(progress);

    if (progress >= 100) {
      clearInterval(timer);
      sdk.startGameAsync()
        .then(function () {
          // Native loading UI removed — the game screen becomes visible from this point
          showGame();
        })
        .catch(function (e) {
          console.error("startGameAsync failed", e.reason, e.message);
        });
    }
  }, 100);
}
```

For the version to use in place of `{{version}}`, see [08. Release Notes](https://onestore-dev.gitbook.io/dev/eng/tools/web-sdk/releasenote).

**Behavior**

<table><thead><tr><th width="200">Item</th><th>Description</th></tr></thead><tbody><tr><td><code>createSDK()</code></td><td>Returns the SDK object. Use this object to configure loading status, start, exit, event reception, and so on. The same instance is returned no matter how many times it is called.</td></tr><tr><td><code>initializeAsync()</code></td><td><p><strong>Idempotent</strong> on success. Calling it again returns the same result. On failure, the internal state is reset, so you can call it again to retry.</p><p>In an unsupported environment (such as a regular browser), it returns <code>{ err: "Platform Not Supported" }</code>. When there is no error, the <code>err</code> field is omitted.</p><p>If initialization fails (no response from the app, etc.), an error is thrown and <code>e.reason</code> is one of the <a href="https://onestore-dev.gitbook.io/dev/eng/tools/web-sdk/errors">error reasons</a> (for example, <code>timeout</code>).</p></td></tr><tr><td><code>startGameAsync()</code></td><td><p>Returns an error if called before <code>initializeAsync</code> completes: <code>e.reason === "sdk_not_initialized"</code></p><p>On success, the app's loading screen is removed and the game screen is shown.</p></td></tr></tbody></table>

{% hint style="info" %}
**Error Object Shape**

The error delivered when a Promise is rejected has `e.reason` (a reason string for branching) and `e.message` (a message for logging). **Numeric error codes are not delivered.** See [06. Error Reasons (reason)](https://onestore-dev.gitbook.io/dev/eng/tools/web-sdk/errors) for details.
{% endhint %}

#### **Showing Loading Progress: setLoadingProgress**

If you report progress while downloading game resources, the progress is shown on the app's native loading screen. You do not need to build a separate loading screen.

* The loading screen is removed when `startGameAsync()` succeeds, not when `setLoadingProgress(100)` is called.
* This is a one-way notification that does not wait for a response. The call does not affect game performance and has no return value.
* `progress` is a number in the range 0 to 100. Values outside the range are clamped to 0 to 100.

#### **initializeAsync Response**

`initializeAsync()` returns only the fields below.

<table><thead><tr><th width="160">Field</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td>playerId</td><td>string</td><td>Pseudonymous per-game user ID. The key under which the game server stores progress data</td></tr><tr><td>locale</td><td>string</td><td>Device UI language (BCP-47, e.g. ko-KR). Use it for number, date and time formatting</td></tr><tr><td>userCountry</td><td>string?</td><td>Service country of the signed-in account (ISO 3166-1 alpha-2, e.g. US). Use it for decisions that depend on the sales country, currency or local regulations. Provided only in the ONE store global app</td></tr><tr><td>userLanguage</td><td>string?</td><td>Display language of the ONE store app (BCP-47, e.g. en, zh-TW). Use it for the game UI language. Provided only in the ONE store global app</td></tr><tr><td>ringerSilent</td><td>boolean</td><td>Whether the device is in silent mode. Use it to decide the initial BGM state. Later changes are delivered via the <code>resume</code> event (see 'Event Listeners' below)</td></tr><tr><td>safeArea</td><td>object</td><td>Insets (px) to keep clear of the system bars: <code>{top, bottom, left, right}</code></td></tr><tr><td>err</td><td>string?</td><td>Present only in unsupported environments. If it has a value, the fields above are not provided</td></tr></tbody></table>

* This information is a one-time snapshot taken at initialization. However, `ringerSilent` may later arrive with a changed value in the `resume` event.
* `safeArea` is an immutable (frozen) object and always returns the same value no matter how many times it is read from the same response object.
* Internal operational fields (session information, app version, etc.) are not provided.
* `userCountry` and `userLanguage` are provided only in the ONE store global app. In other environments they are `undefined`, which is not an error.
* For the game UI language, use `userLanguage` first and fall back to the language part of `locale` (for example, `ko` from `ko-KR`) when it is missing. The device language and the app display language can differ. For example, when the device language is Korean and the ONE store global app is used in English, `locale` is `ko-KR` and `userLanguage` is `en`.
* For decisions that depend on the sales country or currency, use `userCountry`. The region part of `locale` comes from the device settings and cannot stand in for the account country.

{% hint style="info" %}
Feature availability is checked with **per-feature APIs**: `sdk.ads.isSupported()` for ads ([04. In-App Advertising (IAA)](https://onestore-dev.gitbook.io/dev/eng/tools/web-sdk/iaa)) and `sdk.iap.isSupported(feature)` for payments and product details ([05. In-App Purchase (IAP)](https://onestore-dev.gitbook.io/dev/eng/tools/web-sdk/iap)). Supported features may differ by app version, so check before showing UI such as an ad button or shop prices.
{% endhint %}

#### **Event Listeners: pause / resume / exit**

Situations that occur outside the game, such as app switching, ad display, and exit, are delivered as SDK events. Register and remove listeners with `on` / `once` / `off`. We recommend registering listeners before calling `initializeAsync()`, because events may arrive in quick succession right after initialization.

The available events are `"pause"`, `"resume"`, and `"exit"`.

<table><thead><tr><th width="90">Event</th><th width="220">Payload</th><th>When It Fires</th><th>What the Game Should Do</th></tr></thead><tbody><tr><td>pause</td><td><code>{reason: "background" | "ad" | "payment"}</code></td><td>When the app goes to the background, or the game must stop so an ad can be shown</td><td>Immediately stop the game loop, BGM, and sound effects</td></tr><tr><td>resume</td><td><code>{ringerSilent?: boolean}</code></td><td>When the game should run again. <code>ringerSilent</code> is included only if silent mode changed between pause and resume (omitted if unchanged)</td><td>Resume the game</td></tr><tr><td>exit</td><td><code>{}</code></td><td><p>When the app requests the game to exit: the user chose 'Exit' in the back-key exit confirmation popup, the app closes the game screen, and so on</p><p>When the game called <code>restart()</code> (a chance to save right before restarting)</p><p>※ Does not fire when the game itself called <code>quit()</code></p></td><td>Save progress. There is no need to call <code>quit()</code> again. After saving, the SDK finishes the exit automatically and the app continues the exit or restart procedure.</td></tr></tbody></table>

```javascript
sdk.on("pause", function (ev) {
  // ev.reason is "background" | "ad" | "payment"
  pauseGameLoop();
  muteAll();
});

sdk.on("resume", function (ev) {
  // ev.ringerSilent — present only if silent mode changed
  if (typeof ev.ringerSilent === "boolean") applyRingerState(ev.ringerSilent);
  resumeGameLoop();
});

sdk.on("exit", function () {
  saveProgress();   // Save — synchronously, and only work that finishes within 0.5 seconds
});
```

{% hint style="warning" %}
**Notes**

* `exit` fires even if the game did not call anything. The most common path is the user closing the game via the back key or app controls, so **put your save logic in the exit listener** to avoid losing progress data.
* Saving must finish synchronously within **0.5 seconds** of receiving exit. The app closes the game screen within that time, so avoid long-running work.
* `exit` does not fire when the game itself called `sdk.quit()`, because the game has already decided to exit. On this path, finish saving before calling `quit()`.
* A game that has not registered an `exit` listener is closed immediately on an exit request.
* `pause` / `resume` events are delivered while an ad is displayed. The code that called the ad API does not need to stop the game separately; handle it consistently in one pause listener.
* The Android back key is handled with the `onBackPressed()` handler, not an `on()` event (see 'Back Key Handling' below), because whether it was consumed must be returned immediately as a return value.
  {% endhint %}

#### **Exit / Restart: quit / restart**

<table><thead><tr><th width="150">API</th><th width="170">Parameters / Return</th><th>Behavior</th></tr></thead><tbody><tr><td><code>sdk.quit()</code></td><td>None / None</td><td>A request from the game to exit on its own. The exit procedure proceeds immediately without the app's exit confirmation popup. The <code>exit</code> event does not fire in this case, so finish saving before calling it if needed.</td></tr><tr><td><code>sdk.restart()</code></td><td>None / None</td><td>A request to reload (restart) the game. When called, an <code>exit</code> event arrives to give a chance to save, and the app reloads the game page. In the exit handler you only need to save; calling <code>quit()</code> again is unnecessary. After the reload, start again from <code>createSDK()</code> → <code>initializeAsync()</code>.</td></tr></tbody></table>

{% hint style="danger" %}
`restart()` reloads the page. `playerId` is preserved, but unsaved progress data is lost. Be sure to save in the `exit` event.
{% endhint %}

#### **Back Key Handling: onBackPressed**

The game can handle the Android back key first. If the handler returns `true`, the game is considered to have handled it (for example, closing an in-game popup). If it returns `false` or there is no handler, the app's default behavior (exit confirmation popup) proceeds.

```javascript
sdk.onBackPressed(function () {
  if (isPopupOpen()) {
    closePopup();
    return true;    // Consumed by the game — the app does nothing
  }
  return false;     // Not consumed — the app's exit confirmation popup proceeds
});
```

* The handler must be a **synchronous function**. The app waits 200 ms for a reply, so async functions and long-running work cannot be used. If no reply arrives in time, it is treated as not consumed.
* If the handler throws an exception, it is treated as not consumed (false).
* It is treated as consumed only when the return value is exactly `true`.
* If it is treated as not consumed and the user chooses 'Exit' in the exit confirmation popup, an `exit` event arrives (see 'Event Listeners' above).

#### **Opening External Links: openDeeplink**

Navigates to an external link. Call `sdk.openDeeplink(url)`. It returns a Promise.

<table><thead><tr><th width="120">Parameter</th><th width="90">Type</th><th width="90">Required</th><th>Description</th></tr></thead><tbody><tr><td>url</td><td>string</td><td>Required</td><td>Target URL. The app validates the allowed domains. A validation failure is rejected with <code>reason: "invalid_params"</code> (it does not distinguish between an unlisted domain and a format error)</td></tr></tbody></table>

```javascript
sdk.openDeeplink("https://onestore.co.kr/event/summer")
  .catch(function (e) {
    console.warn("navigation failed", e.reason, e.message);   // e.g. "invalid_params"
  });
```
