> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 示例应用：应用内消息

> 示例应用 Clean Beans 如何使用应用内消息触发器和自定义 HTML 实现帮助浮层、权限预提示以及更新和评价提示。

本页面是[示例应用：完整的 OneSignal 集成](https://documentation.onesignal.com/docs/cn/example-full-integration-overview.md)的一部分，该指南从头到尾跟随一个真实应用。这个应用是 **Clean Beans**，一款面向合租家庭的打扫值日表应用，使用 Expo（React Native）和 Supabase 后端构建。

应用内消息会在用户使用应用时显示。它们的内容、受众和计划都保存在 OneSignal 仪表板中，因此无需发布新版本即可更改。Clean Beans 将它们用于五项工作。

| 消息 | 显示时机 | 定向方式 |
| - | - | - |
| 帮助浮层 | 用户点击某个界面上的帮助按钮 | 应用设置的触发器 |
| 引导 | 用户需要某个界面的引导教程 | 同一个触发器 |
| 推送权限预提示 | 在系统权限对话框之前 | 仪表板中的受众和计划 |
| 应用更新提示 | 用户使用的是旧版本 | 细分 |
| 评价提示 | 用户达到连续记录里程碑 | 应用设置的触发器 |

## 触发器：由应用决定时机 \\

触发器是应用设置的一个键和值。所有配置为与之匹配的应用内消息都会显示。Clean Beans 的每个界面在标题栏都有一个帮助按钮，它会以界面名称作为值设置一个触发器。

```typescript src/components/HelpButton.tsx theme={null}
export function HelpButton({ triggerValue }: HelpButtonProps) {
  const handlePress = () => {
    OneSignal.InAppMessages.addTrigger('help_topic', triggerValue);
  };

  return (
    <TouchableOpacity onPress={handlePress} style={styles.button} hitSlop={8}>
      <Ionicons name="help-circle-outline" size={26} color={Colors.white} />
    </TouchableOpacity>
  );
}
```

```typescript app/(tabs)/_layout.tsx theme={null}
<Tabs.Screen
  name="index"
  options={{
    title: 'Dashboard',
    headerRight: () => <HeaderRight helpTopic="dashboard" />,
    tabBarIcon: ({ focused }) => <TabIcon name={focused ? 'home' : 'home-outline'} focused={focused} />,
  }}
/>
```

一个触发器键服务于十三个界面。为新界面添加帮助，只需添加一个带新值的按钮，并在仪表板中创建一条消息。

![显示在仪表板上方的帮助浮层应用内消息](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-help.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=521ce92f66d1df24e99790600813523a)

点击仪表板上的帮助按钮会显示帮助浮层。

**仪表板设置。** 在 **Messages > In-App** 中，创建一条触发器为 `help_topic` **is** `dashboard` 的消息，并为每个界面重复此操作。多步骤引导使用相同的触发器和轮播布局。

![由可滑动卡片组成的引导应用内消息](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-iam-walkthrough.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=c335375ee2bb79060e97aa945dea644e)

以卡片轮播形式构建的多步骤引导。

## 自定义 HTML 消息 \\

帮助浮层用 HTML 编写，因此与应用的设计完全一致。HTML 应用内消息通过 `OneSignalIamApi` 对象与 SDK 通信。每个可点击元素都适用两条规则：

* 为其设置唯一的 `data-onesignal-unique-label`，以便正确跟踪点击。
* 为其绑定一个调用 `OneSignalIamApi` 方法的监听器。普通链接不会被跟踪。

```html docs/iam-html/help-dashboard.html theme={null}
<button id="got-it" class="cta-btn" data-onesignal-unique-label="dashboard-got-it">Got it</button>

<script>
  document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("got-it").addEventListener("click", function (e) {
      OneSignalIamApi.close(e);
    });
  });
</script>
```

## 推送权限预提示 \\

系统权限对话框只能显示一次。先显示一条应用内消息可以说明用户将收到什么，只有点击 **Enable notifications** 的人才会看到系统对话框。

![说明开启通知好处的应用内消息](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-iam-push-prompt.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=18791e9af52a803d41048eba393109f6)

预提示会在系统对话框出现之前说明好处。

```html docs/iam-html/push-permission-prompt.html theme={null}
<script>
  document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("enable-btn").addEventListener("click", function (e) {
      OneSignalIamApi.triggerPushPrompt(e);
    });
    document.getElementById("skip-btn").addEventListener("click", function (e) {
      OneSignalIamApi.close(e);
    });
  });
</script>
```

> [!NOTE]
>
> 如果使用预提示，请从应用启动代码中移除 `requestPermission()` 调用。否则系统对话框会先出现，预提示就没有什么可问的了。

## 应用更新提示 \\

新版本发布后，仍在使用旧版本的用户会看到更新提示。这条消息完全不需要应用中的代码。它的受众是使用旧版应用的用户细分。

![请用户更新应用的应用内消息](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-iam-app-version.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=f096ce85f566823331171e14312e534d)

仅向使用旧版本的用户显示的更新提示。

一条消息同时服务两个平台。脚本根据设备选择应用商店，`openUrl` 会跟踪点击、打开应用商店并关闭消息。

```html docs/iam-html/app-update-prompt.html theme={null}
<script>
  var IOS_URL = "https://apps.apple.com/app/id" + IOS_APP_STORE_ID;
  var ANDROID_URL = "https://play.google.com/store/apps/details?id=" + ANDROID_PACKAGE;

  // One message serves both platforms: pick the store from the device.
  var isAndroid = /android/i.test(navigator.userAgent);
  var storeUrl = isAndroid ? ANDROID_URL : IOS_URL;

  document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("update-btn").addEventListener("click", function (e) {
      // openUrl tracks the click, opens the store and closes the message
      OneSignalIamApi.openUrl(e, storeUrl);
    });
    document.getElementById("later-btn").addEventListener("click", function (e) {
      OneSignalIamApi.close(e);
    });
  });
</script>
```

问候语使用标签，并为没有该标签的用户提供默认值。

```html docs/iam-html/app-update-prompt.html theme={null}
<p>Hey {{ user_name | default: "there" }}, you're on an older version</p>
```

**仪表板设置。** 创建一个筛选条件为 **App version** 小于当前版本的细分，并将其用作消息的受众。每次发布新版本时更新该筛选条件。

> [!NOTE]
>
> 标签替换适用于 HTML 应用内消息的文本和属性，但不适用于 `script` 标签内部。

## 评价提示：把点击交还给应用 \\

请求应用商店评分的好时机，是在某件事顺利完成之后。当一次打扫会话让连续记录达到七天的倍数时，Clean Beans 会发出请求。

这是唯一一条点击后必须在应用中运行代码的应用内消息，因为原生评分面板只能由应用自己打开。

**1. 应用在连续记录里程碑设置触发器**

它会等到会话界面关闭，以免提示打断打扫，并记住上次请求时的里程碑。

```typescript src/lib/reviewPrompt.ts theme={null}
export async function maybeAskForReview(streak: number): Promise<void> {
  try {
    if (streak <= 0 || streak % STREAK_MILESTONE_DAYS !== 0) return;

    // A second session on the same day leaves the streak unchanged —
    // don't ask twice for the same milestone.
    const lastPrompted = await AsyncStorage.getItem(LAST_PROMPTED_STREAK_KEY);
    if (lastPrompted === String(streak)) return;
    await AsyncStorage.setItem(LAST_PROMPTED_STREAK_KEY, String(streak));

    OneSignal.InAppMessages.addTrigger(REVIEW_TRIGGER_KEY, REVIEW_TRIGGER_VALUE);
    console.log('[reviewPrompt] Trigger set at streak', streak);
  } catch (e) {
    console.warn('[reviewPrompt] maybeAskForReview error:', e);
  }
}
```

**2. 消息将点击名称发回应用**

`addClickName` 会将名称传给应用的点击监听器。它不会关闭消息，因此脚本随后会关闭消息。

```html docs/iam-html/review-prompt.html theme={null}
<script>
  document.addEventListener("DOMContentLoaded", function () {
    var autoCloseBtn = document.getElementById("auto-close-btn");

    document.getElementById("rate-btn").addEventListener("click", function (e) {
      // Passes the click name "review" to the app's In-App Message click
      // listener, which opens the native rating sheet. addClickName does not
      // close the message, so close it straight afterwards.
      OneSignalIamApi.addClickName(e, "review");
      setTimeout(function () { autoCloseBtn.click(); }, 300);
    });
    autoCloseBtn.addEventListener("click", function (e) {
      OneSignalIamApi.close(e);
    });
    document.getElementById("later-btn").addEventListener("click", function (e) {
      OneSignalIamApi.close(e);
    });
  });
</script>
```

**3. 应用打开原生评分面板**

点击监听器检查名称，并请求系统显示评分面板。

```typescript src/lib/reviewPrompt.ts theme={null}
export function handleReviewClick(event: InAppMessageClickEvent): void {
  if (event.result.actionId !== REVIEW_ACTION_ID) return;

  // Give the In-App Message a moment to close before presenting the sheet
  setTimeout(async () => {
    try {
      // false on TestFlight builds and on the web
      if (await StoreReview.isAvailableAsync()) {
        await StoreReview.requestReview();
      } else {
        console.log('[reviewPrompt] Store review not available on this build');
      }
    } catch (e) {
      console.warn('[reviewPrompt] requestReview error:', e);
    } finally {
      // Clear the trigger so the message is not re-evaluated this app session
      OneSignal.InAppMessages.removeTrigger(REVIEW_TRIGGER_KEY);
    }
  }, 800);
}
```

```typescript app/_layout.tsx theme={null}
OneSignal.InAppMessages.addEventListener('click', handleReviewClick);
```

![评价提示应用内消息](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-review-prompt.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=90dde058450240f49d42e76402ed28ce)

评价提示应用内消息。

**仪表板设置。** 创建一条触发器为 `ask_for_review` **is** `show` 的 HTML 应用内消息。将其计划设置为最多每 17 周显示一次。

> [!WARNING]
>
> Apple 每年对每位用户最多显示三次评分面板，Google 也有自己的限制，因此点击按钮并不保证一定会显示任何内容。TestFlight 构建中永远不会出现评分面板。请使用 App Store 构建测试此流程。

> [card] [应用内触发器](https://documentation.onesignal.com/docs/cn/iam-triggers.md)
>
> 触发器类型及其组合方式。

> [card] [HTML 应用内消息](https://documentation.onesignal.com/docs/cn/design-your-in-app-message-with-html.md)
>
> 使用您自己的 HTML 设计消息。

> [card] [应用内 JavaScript API](https://documentation.onesignal.com/docs/cn/in-app-message-api.md)
>
> 所有 `OneSignalIamApi` 方法。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.