廣告位招商中 歡迎洽談

在 Poe 上構建與變現互動式 Canvas 應用:開發者完整指南

松下祥子 · 365Finds Editorial
已收錄 88,650 篇 Wiki 文章

讓你的 AI 用上 365 Wiki

複製下方的提示詞,貼給你常用的 AI,然後直接提問。

下載完整版 Skill

先用提示詞體驗;經常使用時,安裝完整版 365Wiki Skill,以後無需重複複製。沒有常用 AI?Gemini、Microsoft Copilot 等網頁版也可以。

365Wiki Skill

純文字與 Markdown 對話機器人的互動形態正逐漸遭遇明顯的瓶頸。當你需要呈現互動式儀表板、圖像編輯畫布、動態模擬器或多參數配置面板時,單純要求大模型輸出長篇對話文字,不僅體驗拖沓,也無法提供直觀的操作反饋。

Poe 透過 Previews(即時預覽) 與 Canvas 應用 打破了這個限制。它允許開發者構建運行於 Poe 宿主環境中的單檔案用戶端 Web 應用。平台向沙箱安全環境自動注入全域 window.Poe 嵌入式 API,前端開發者得以直接與底層大語言模型雙向通訊、將串流生成結果即時掛載到 DOM、運用狀態同步庫維護應用資料,並透過計算點數(Compute Points)機制實現商業化變現。

365Finds 的核心判斷非常堅定:對於超過 80% 的前端互動型 AI 工具,Canvas 應用的效益遠勝於自行架設 FastAPI Server Bot。 開發者無需負擔伺服器營運成本、容器維護與複雜的 CORS 鑑權流程,便能直接接入 Poe 的全球分發管道與點數計費體系。然而,開發者也必須充分掌握其嚴格的沙箱運行限制,包括 iframe 隔離、受限的本地儲存以及嚴格的內容安全策略(CSP)。


1. 架構剖析:Previews 與 Canvas 應用的運作機制

在著手編寫程式碼之前,必須先理解 Poe 的前端渲染與執行架構:

沙箱安全邊界與開發者避坑對照表

由於應用完全在前端沙箱中執行且預設無專屬後端伺服器,開發者必須遵守以下平台規格與限制:

約束維度平台限制與安全規範開發者應對策略與最佳實踐
部署載體純用戶端執行;必須整合成單一 HTML 檔案利用 Vite 單檔案打包外掛或引入官方白名單 CDN 資源(如 React、Vue、Tailwind)
外部資源與 CSP嚴格的內容安全策略;僅允許信任來源(如 cdnjs.cloudflare.com、cdn.jsdelivr.net)避免引用非白名單的第三方網域,防止觸發使用者端的全螢幕安全攔截警告
資料持久化瀏覽器原生 localStorage 與 IndexedDB 均被停用採用平台原生的 Synced Store(Poe.setupStore)或向專屬 Server Bot 傳送資料
原生彈窗 API沙箱缺少 allow-modals 權限,呼叫 alert()、confirm()、prompt() 會拋出錯誤改以 HTML/CSS 在應用內自訂模態對話框(Modal)與浮動通知(Toast)
硬體與剪貼簿攝影機與麥克風權限禁用;剪貼簿僅開放寫入無法主動讀取提供應用內複製按鈕;使用者素材由檔案上傳輸入框(<input type="file">)載入
超連結導航同源相對路徑導航無效;外部跨網域連結點擊將觸發平台安全確認提示採用用戶端純前端路由;檔案下載統一透過 blob: 協議動態生成臨時連結

2. Poe Embed API 核心方法解析

全域物件 window.Poe 是連結前端視覺化介面與 Poe 底層多模型矩陣的溝通橋樑。

window.Poe.getTriggerMessage()

讀取觸發 Canvas 畫布開啟的原始訊息物件。當使用者從對話中點擊按鈕或由特定提示詞啟動應用時,此方法能讓畫布第一時間獲取使用者初始的文字輸入與上傳的附件檔案。

const trigger = await window.Poe.getTriggerMessage();
if (trigger) {
  console.log("觸發角色:", trigger.role); // 'user' 或 'bot'
  console.log("使用者初始 Prompt:", trigger.text);
  if (trigger.attachments?.length > 0) {
    console.log("使用者上傳的附件:", trigger.attachments);
  }
}

window.Poe.sendUserMessage() 與 window.Poe.registerHandler()

這組方法構成了應用程式與模型溝通的核心管道。Canvas 應用可代表當前使用者發送訊息給指定的機器人(例如 @Claude-3.5-Sonnet 或 @GPT-4o),並透過預先註冊的處理常式非同步接收模型串流吐出或完整產生的內容。

// 1. 註冊回呼處理常式以接收模型回應
window.Poe.registerHandler("dashboardAnalyzer", (result, context) => {
  const message = result.responses[0];
  const outputElement = document.getElementById("ai-output");
  
  if (message) {
    outputElement.textContent = message.content;
    
    if (message.status === "complete") {
      outputElement.classList.remove("loading");
      console.log("分析完成,任務代號:", context.taskId);
    } else if (message.status === "error") {
      outputElement.classList.add("error");
      console.error("生成失敗:", message.statusText);
    }
  }
});

// 2. 發起大模型查詢
async function triggerAnalysis(dataPayload) {
  try {
    const response = await window.Poe.sendUserMessage(
      `@Claude-3.5-Sonnet 請分析以下資料並整理出三個核心洞察:\n${dataPayload}`,
      {
        stream: true,
        openChat: false, // 讓使用者專注於畫布介面,不強制彈出對話窗
        handler: "dashboardAnalyzer",
        handlerContext: { taskId: "task_001" }
      }
    );
    if (!response.success) {
      console.warn("訊息傳送未成功");
    }
  } catch (err) {
    // 可能拋出的錯誤:INVALID_INPUT、USER_REJECTED_CONFIRMATION、ANOTHER_CONFIRMATION_IS_OPEN
    console.error("呼叫 Embed API 發生異常:", err);
  }
}

即時串流與主對話串同步擴充

在最新版 Embed API(草案 V2)中,平台進一步提供了現代化非同步迭代器與對話串寫入工具:


3. 解決無狀態限制:Synced Store 資料同步架構

針對沙箱環境無法使用 localStorage 的限制,Poe 推出了 Synced Store(window.Poe.setupStore)。透過在獨立配置標籤中宣告 Mutators(變更函式),為 Canvas 應用帶來具備事務一致性的資料讀寫與多端即時同步能力。

<!-- 儲存配置必須置於獨立的 script 標籤中 -->
<script id="poe-store-config">
Poe.setupStore({
  mutators: {
    async setWorkspaceState(tx, { documentId, nodes, activeFilter }) {
      await tx.table("workspaces").set(documentId, {
        nodes,
        activeFilter,
        updatedAt: Date.now()
      });
    }
  }
});
</script>

<script>
// 在前端主程式中訂閱與更新狀態
const store = window.Poe.store;

// 訂閱資料庫變更以即時重新繪製介面
store.subscribe(
  async (ctx) => await ctx.table("workspaces").entries().toArray(),
  (records) => {
    renderCanvasView(records);
  }
);

// 執行事務變更
async function saveProject(docId, currentNodes) {
  await store.mutate.setWorkspaceState({
    documentId: docId,
    nodes: currentNodes,
    activeFilter: "all"
  });
}
</script>

4. 實戰範例:構建概念分解思維導圖 Canvas 應用

以下提供一個結構完整的單檔案 Canvas 應用範本,展示如何向大模型請求 JSON 結構化資料並即時渲染為視覺化互動卡片:

<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>互動式概念分解看板</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.js"></script>
  <style>
    .node-card { transition: all 0.2s ease-in-out; }
    .node-card:hover { transform: translateY(-2px); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
  </style>
</head>
<body class="bg-gray-50 text-gray-900 p-6">
  <div class="max-w-4xl mx-auto">
    <header class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold">概念互動分解畫布</h1>
      <button id="btn-export" class="px-4 py-2 bg-blue-600 text-white rounded shadow hover:bg-blue-700">匯出節點</button>
    </header>

    <div class="mb-4">
      <textarea id="topic-input" rows="3" class="w-full p-3 border rounded shadow-sm focus:ring-2 focus:ring-blue-500" placeholder="輸入你想拆解的主題或商業命題..."></textarea>
      <button id="btn-submit" class="mt-2 px-5 py-2 bg-indigo-600 text-white font-medium rounded shadow hover:bg-indigo-700">開始推理並拆解</button>
    </div>

    <div id="cards-container" class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
      <div class="p-4 bg-white border border-gray-200 rounded-lg text-gray-400 italic">尚無節點,請輸入主題後開始生成。</div>
    </div>
  </div>

  <script>
    // 註冊 Embed API 回應處理常式
    window.Poe.registerHandler("mindmapHandler", (result) => {
      const resp = result.responses[0];
      const container = document.getElementById("cards-container");

      if (resp && resp.content) {
        try {
          // 清理 Markdown 標記並解析 JSON
          const raw = resp.content.replace(/```json|```/g, "").trim();
          const parsed = JSON.parse(raw);
          container.innerHTML = "";
          parsed.nodes.forEach(node => {
            const card = document.createElement("div");
            card.className = "node-card p-4 bg-white border border-indigo-100 rounded-lg shadow-sm";
            card.innerHTML = `<h3 class="font-semibold text-indigo-700 mb-1">${node.title}</h3><p class="text-sm text-gray-600">${node.detail}</p>`;
            container.appendChild(card);
          });
        } catch (e) {
          if (resp.status === "incomplete") {
            container.innerHTML = `<div class="p-4 bg-white border rounded text-indigo-600">正在串流解析概念節點...</div>`;
          }
        }
      }
    });

    document.getElementById("btn-submit").addEventListener("click", async () => {
      const topic = document.getElementById("topic-input").value.trim();
      if (!topic) return;

      const prompt = `請針對主題「${topic}」進行概念拆解,以標準 JSON 回傳 4 個子要點。格式:{"nodes": [{"title": "名稱", "detail": "說明"}]}。請僅回傳 JSON 字串,無需多餘文字。`;
      
      await window.Poe.sendUserMessage(`@Claude-3.5-Sonnet ${prompt}`, {
        stream: true,
        openChat: false,
        handler: "mindmapHandler"
      });
    });

    // 透過 Blob 實現純前端資料匯出
    document.getElementById("btn-export").addEventListener("click", () => {
      const content = document.getElementById("cards-container").innerText;
      const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = "mindmap-nodes.txt";
      link.click();
    });
  </script>
</body>
</html>

5. 商業化機制:計算點數(Compute Points)與微美分定價

開發出實用的工具只是起點,獲取商業收益才是獨立創作者持續迭代的動力來源。Poe 採取了雙層經濟體系:

  1. 使用者端視角:計算點數(Compute Points):使用者在 Poe 上的各項呼叫均以消耗帳戶內的計算點數結算。
  2. 創作者端定價:微美分(USD milli-cents):創作者以微美分標註服務價格(1 美元 = 100,000 微美分;1 美分 = 1,000 微美分)。Poe 系統會自動將該美元定價動態轉換為向使用者扣除的等價計算點數。

變現管道 A:配置機器人層級單次互動費

於創作者中心(poe.com/creators)直接為 Canvas 應用設定使用費用:

變現管道 B:應用內即時精細化收費 window.Poe.captureCost()

若你的 Canvas 應用包含豐富功能,採用「基礎功能免費、高階生成按次收費」是轉換率最佳的模型。利用 Embed API 的 captureCost 方法即可在特定動作觸發時扣除點數:

async function unlockAdvancedFeature() {
  const PREMIUM_FEE = 50000; // 50,000 微美分 = 0.50 美元

  try {
    // 請求扣除使用者相應的計算點數
    const result = await window.Poe.captureCost(
      [
        {
          amountUsdMilliCents: PREMIUM_FEE,
          description: "高階產業資料視覺化分析"
        }
      ],
      { logChargeOutcome: true }
    );

    if (result.success) {
      console.log("扣款成功,開始執行高階運算");
      runHeavyWorkflow();
    } else {
      showToastNotification("扣款未能完成,請確認計算點數餘額。");
    }
  } catch (error) {
    // 妥善處理 USER_REJECTED_CONFIRMATION 或餘額不足等異常
    console.error("扣款發生錯誤:", error);
    showToastNotification("授權扣款失敗,請稍後再試。");
  }
}

6. 365Finds 機構評估與決策建議

綜合產品架構與市場商業化現狀,365Finds 提供開發者以下關鍵判斷:


參考資料