React 與 Next.js
將代理程式小工具加入 React 與 Next.js 應用程式。
只要幾行程式碼,就能將代理程式小工具整合進 React 與 Next.js 應用程式。
安裝
將小工具指令碼加入你的 React 應用程式。先從 Chatbot > 發布 取得嵌入程式碼,再依你使用的框架調整。
Next.js(App Router)
使用 Next.js 的 Script 元件,將指令碼加入根版面配置:
// app/layout.tsx
import Script from 'next/script';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
{children}
{/* Get your src and data-chatbot values from Chatbot > Publish */}
<Script
src="YOUR_WIDGET_URL"
data-chatbot="YOUR_CHATBOT_ID"
strategy="afterInteractive"
/>
</body>
</html>
);
}
Next.js(Pages Router)
加入到 _app.tsx 或 _document.tsx:
// pages/_app.tsx
import Script from 'next/script';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
{/* Get your src and data-chatbot values from Chatbot > Publish */}
<Script
src="YOUR_WIDGET_URL"
data-chatbot="YOUR_CHATBOT_ID"
strategy="afterInteractive"
/>
</>
);
}
Create React App
加入到 public/index.html,並從 Chatbot > 發布 複製你的嵌入程式碼:
<!DOCTYPE html> <html lang="en"> <head> <!-- ... --> </head> <body> <div id="root"></div> <!-- Paste your embed code from Chatbot > Publish here --> </body> </html>
Vite
加入到 index.html,並從 Chatbot > 發布 複製你的嵌入程式碼:
<!DOCTYPE html> <html lang="en"> <head> <!-- ... --> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> <!-- Paste your embed code from Chatbot > Publish here --> </body> </html>
動態代理程式 ID
若是多租戶應用程式,代理程式 ID 會依情境不同:
// components/ChatbotWidget.tsx
'use client';
import Script from 'next/script';
interface ChatbotWidgetProps {
chatbotId: string;
widgetUrl: string;
}
export function ChatbotWidget({ chatbotId, widgetUrl }: ChatbotWidgetProps) {
if (!chatbotId) return null;
return (
<Script
src={widgetUrl}
data-chatbot={chatbotId}
strategy="afterInteractive"
/>
);
}
條件式載入
僅在特定頁面顯示小工具:
// app/support/layout.tsx
import Script from 'next/script';
export default function SupportLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
{children}
{/* Get your src and data-chatbot values from Chatbot > Publish */}
<Script
src="YOUR_WIDGET_URL"
data-chatbot="YOUR_CHATBOT_ID"
strategy="afterInteractive"
/>
</>
);
}
TypeScript 型別
小工具不需要 TypeScript 型別,因為它是從外部載入,並自行管理自己的介面。
開發期間的測試
在本機開發時:
- 將
localhost加入允許的網域 - 使用你的正式環境代理程式 ID
- 照常測試互動流程
環境變數
將代理程式 ID 與小工具網址儲存在環境變數中:
# .env.local NEXT_PUBLIC_CHATBOT_ID=your-chatbot-id NEXT_PUBLIC_WIDGET_URL=your-widget-url
<Script
src={process.env.NEXT_PUBLIC_WIDGET_URL}
data-chatbot={process.env.NEXT_PUBLIC_CHATBOT_ID}
strategy="afterInteractive"
/>
這兩個值都可以在你代理程式的發布分頁中取得。
伺服器元件說明
Script 元件可與 React 伺服器元件搭配使用。你不需要將版面配置標記為用戶端元件。
後續步驟
- 自訂小工具外觀
- 設定網域限制
- 若想打造自訂介面,請使用 REST API