> For the complete documentation index, see [llms.txt](https://docs.hackle.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hackle.io/development-guide/flutter/flutter-webapp-integration.md).

# 웹앱 연동

[flutter\_inappwebview](https://pub.dev/packages/flutter_inappwebview)의 `InAppWebView`에 핵클 웹뷰 브릿지를 설정하면 웹사이트의 JavaScript SDK 호출을 Flutter SDK로 전달합니다. 웹뷰에서 발생하는 핵클 이벤트는 Flutter SDK에서 수집하며, 앱과 웹에서 동일한 사용자 식별자를 사용합니다. [웹앱 연동 개요](https://docs.hackle.io/development-guide/faq/web-app-intergration.md)를 참고하세요.

{% stepper %}
{% step %}

### 앱과 웹의 SDK 초기화

앱에서 [Flutter SDK를 초기화](https://docs.hackle.io/development-guide/flutter.md#sdk-initialization)하고 `await HackleApp.initialize(...)`가 완료된 뒤 웹뷰를 생성하세요. 웹페이지의 [JavaScript SDK](https://docs.hackle.io/development-guide/javascript.md)도 Flutter SDK 초기화에 사용한 것과 **동일한 App SDK 키**로 초기화하세요.
{% endstep %}

{% step %}

### 웹뷰 브릿지 설정 <a href="#webview-bridge-settings" id="webview-bridge-settings"></a>

`initialUserScripts`에 브릿지 스크립트를 추가해 문서 로드 시작 시점에 주입합니다. 비동기 호출을 처리하려면 `messageChannel: true`를 설정하고, `onWebViewCreated`에서 메시지 채널 핸들러를 등록한 뒤 `controller.loadUrl`로 웹페이지를 로드하세요. 예제의 `YOUR_WEB_URL`에 웹페이지 주소를 넣으세요.

```dart
import 'dart:collection';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hackle/hackle.dart';

final keepAlive = InAppWebViewKeepAlive();

InAppWebView(
  initialSettings: InAppWebViewSettings(
    javaScriptEnabled: true,
  ),
  keepAlive: keepAlive,
  initialUserScripts: UnmodifiableListView<UserScript>([
    UserScript(
      source: HackleApp.getWebBridgeScript(messageChannel: true),
      injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,
      forMainFrameOnly: true,
    ),
  ]),
  onWebViewCreated: (controller) {
    controller.addJavaScriptHandler(
      handlerName: HackleApp.webViewMessageHandlerName,
      callback: HackleApp.webViewMessageHandler,
    );
    controller.loadUrl(urlRequest: URLRequest(url: WebUri('YOUR_WEB_URL')));
  },
  onJsPrompt: (controller, request) async {
    final message = request.message;
    if (await HackleApp.isInvocableCommandInWebView(message)) {
      final result = await HackleApp.handleWebInterfaceCommand(message);
      return JsPromptResponse(
        action: JsPromptResponseAction.CONFIRM,
        handledByClient: true,
        value: result,
      );
    }
    return JsPromptResponse(handledByClient: false);
  },
);
```

{% hint style="info" %}
메시지 채널은 Flutter SDK 3.0.0 이상과 JavaScript SDK 12.1.0 이상에서 지원합니다. 기본 웹뷰 브릿지는 Flutter SDK 2.13.0 이상과 JavaScript SDK 11.25.1 이상에서 지원합니다. 기본 웹뷰 브릿지만 사용하는 경우 `getWebBridgeScript()`를 호출하고, `onWebViewCreated`에는 `controller.loadUrl` 호출만 넣으세요.
{% endhint %}

{% hint style="warning" %}
Android에서 `DOCUMENT_START_SCRIPT`를 지원하지 않는 환경에서는 브릿지 스크립트가 웹페이지의 다른 리소스보다 먼저 실행된다는 보장이 없습니다. 자세한 내용은 [InAppWebView의 User Scripts 문서](https://inappwebview.dev/docs/webview/javascript/user-scripts/)를 참고하세요.

웹페이지가 `beforeunload` 또는 `unload` 시점에 이벤트를 전송한다면, 예제처럼 [KeepAlive](https://inappwebview.dev/docs/webview/keep-alive/)를 설정해 Flutter 위젯 트리에서 웹뷰가 제거된 뒤에도 네이티브 웹뷰를 유지하세요.
{% endhint %}
{% endstep %}
{% endstepper %}

## 웹뷰에서 발생하는 자동 수집 이벤트 연동 <a href="#webview-auto-collected-events" id="webview-auto-collected-events"></a>

{% hint style="info" %}
Flutter SDK 2.26.0 이상, JavaScript SDK 11.51.0 이상 버전에서 지원하는 기능입니다.
{% endhint %}

웹뷰의 `$page_view`와 `$engagement` 자동 수집은 기본적으로 꺼져 있습니다. 아래 설정을 만든 뒤, 웹뷰 설정 예제의 `getWebBridgeScript` 호출에 `webViewConfig: webViewConfig` 인수를 추가하세요.

```dart
final webViewConfig = HackleWebViewConfig.builder()
    .automaticScreenTracking(true)
    .automaticEngagementTracking(true)
    .build();
```

### 설정 옵션 <a href="#config-options" id="config-options"></a>

<table><thead><tr><th width="258.32421875">Option</th><th width="120">Default</th><th>Description</th><th width="150">지원 버전</th></tr></thead><tbody><tr><td><code>automaticScreenTracking</code></td><td><code>false</code></td><td>웹사이트에서 발생하는 <code>$page_view</code> 수집 여부</td><td>2.26.0+</td></tr><tr><td><code>automaticEngagementTracking</code></td><td><code>false</code></td><td>웹사이트에서 발생하는 <code>$engagement</code> 수집 여부</td><td>2.28.0+</td></tr><tr><td><code>automaticRouteTracking</code></td><td><code>true</code></td><td>웹사이트에서 발생하는 페이지 정보 자동 수집 여부</td><td>2.28.0+<br>(JavaScript SDK 11.53.0+)</td></tr></tbody></table>

{% hint style="info" %}
웹페이지 이동 시 `$page_view`와 `$engagement`를 자동 수집하려면 `automaticScreenTracking`, `automaticEngagementTracking`, `automaticRouteTracking`를 모두 `true`로 설정하세요.

웹페이지 이동 시 `$page_view`와 `$engagement`를 [수동 수집](https://docs.hackle.io/development-guide/javascript/event-tracking/js-track-page.md)하는 경우 `automaticScreenTracking`, `automaticEngagementTracking`는 `true`로 설정하고, `automaticRouteTracking`를 `false`로 설정하세요.
{% endhint %}


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.hackle.io/development-guide/flutter/flutter-webapp-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
