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

# 安裝聊天小工具

> 把 TinyInbox 聊天小工具加入你的網站。

每個 TinyInbox 網站都有自己的小工具程式碼。把它安裝到需要讓訪客聯絡你的頁面。

## 複製程式碼

在儀表板打開 **Install widget**，選擇網站後複製該網站的 script 標籤。

```html theme={null}
<script
  async
  src="https://api.tinyinbox.co/widget.js"
  data-tinyinbox-site="tin_your_site_key"
  data-tinyinbox-language="auto"
></script>
```

## 貼到你的網站

把 script 貼到 `</body>` 前面。多數網站架設工具和 CMS 都有自訂程式碼區塊可以使用。

請使用儀表板提供的完整程式碼。每個網站都有唯一的網站金鑰。

## 建議的應用程式模式

小工具 script 是 async 載入。如果你的產品需要設定文案、語言或訪客身分，請在 TinyInbox ready 之後，從 client-only code 呼叫。請使用你的框架在 hydration 後、auth state 已知時執行的 client-only route/component boundary 或 loader。

不要在 server rendering 或 component render 期間直接呼叫 `window.TinyInbox`。這些階段可能執行多次、被重新播放，或發生在 async 小工具 runtime ready 之前。

對於使用 signed identity 的已登入 app 使用者，請繼續使用儀表板複製的 script，並在 auth state 已知後透過 `TinyInbox.identify` 傳入 signed `identityToken`。不要在應用程式碼裡重新組合 widget URL 或 site key。

## 設定訪客語言

`data-tinyinbox-language` 可使用 `auto`、`en` 或 `zh-tw`。`auto` 會讀取頁面或瀏覽器語言。

如果你的產品本身有語言切換器，可以在小工具載入後設定 TinyInbox。訪客切換語言時，也可以再次呼叫。

```js theme={null}
const tinyInboxLanguage =
  (currentUser.language || "").replace(/_/g, "-").toLowerCase() === "zh-tw"
    ? "zh-tw"
    : "en"

function onTinyInboxReady(callback) {
  if (window.TinyInbox && window.TinyInbox.isReady) {
    callback(window.TinyInbox)
    return
  }

  window.addEventListener(
    "tinyinbox:ready",
    (event) => callback(event.detail),
    { once: true }
  )
}

onTinyInboxReady((TinyInbox) => {
  TinyInbox.configure({
    language: tinyInboxLanguage,
    welcomeMessage: translate("support.chatWelcome"),
    labels: {
      send: translate("support.send"),
      messagePlaceholder: translate("support.messagePlaceholder"),
    },
  })
})
```

## Origin 檢查

小工具的 session 請求必須來自該網站允許的 origins。TinyInbox 會在發出小工具 session token 前檢查瀏覽器的 `Origin` 或 `Referer`。

## 加入訪客資訊

如果你的網站已經知道訪客姓名或 email，可以在小工具載入後傳給 TinyInbox。

這個瀏覽器提供身分的模式適用於沒有使用 signed identity token 的情境。對於已登入的產品使用者，建議使用 signed token 流程，且不要再為同一位訪客另外呼叫一次瀏覽器端的 name/email identify。

```js theme={null}
function onTinyInboxReady(callback) {
  if (window.TinyInbox && window.TinyInbox.isReady) {
    callback(window.TinyInbox)
    return
  }

  window.addEventListener(
    "tinyinbox:ready",
    (event) => callback(event.detail),
    { once: true }
  )
}

onTinyInboxReady((TinyInbox) => {
  TinyInbox.identify({
    name: currentUser.name,
    email: currentUser.email,
  })
})
```

如果訪客已登入，且你需要讓後端信任訪客 ID、姓名或 email，請使用[已登入訪客辨識](/zh-Hant/guides/identity-verification)。
