You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于用户输入动态生成不同postMessage回复并实现多存档功能

Implementing Multi-Save Functionality with postMessage and concat()

Got it, let's walk through how to build this multi-save system alongside your existing postMessage setup for the iframe game. The core idea is bundling individual save states into a single string (using concat() or cleaner alternatives) that you can send/receive, then split back into separate saves when needed.

1. Structure Your Individual Save Data

First, make sure each save state is a stringified JSON object—this makes serialization/deserialization straightforward. For example:

// Inside your iframe game: Create a single save state
const saveSlot1 = JSON.stringify({
  score: 1800,
  level: 6,
  unlockedItems: ["fire wand", "health potion"]
});

const saveSlot2 = JSON.stringify({
  score: 3200,
  level: 10,
  unlockedItems: ["ice shield", "teleport scroll"]
});

2. Merge Saves with concat()

Use concat() to combine these save strings, and add a unique delimiter (like ###) that won't appear in your save data—this lets you split them later without breaking the JSON.

// Merge multiple saves into one string
const combinedSaves = saveSlot1.concat("###", saveSlot2);
// Result: '{"score":1800,...}###{"score":3200,...}'

Quick note: Template literals are often more readable for this: ${saveSlot1}###${saveSlot2}—same end result, just easier to write.

3. Send the Combined Saves via postMessage

Send the bundled string to the parent window (or vice versa, depending on your flow). Don't forget to lock down the origin for security!

// Inside iframe: Send combined saves to parent
window.parent.postMessage({
  type: "save",
  payload: combinedSaves
}, "https://your-parent-domain.com"); // Replace with your actual parent origin

4. Receive and Parse the Combined Saves

On the receiving end (parent or iframe), split the string back into individual saves using your delimiter, then parse each one back to an object:

// Parent window: Listen for postMessage events
window.addEventListener("message", (event) => {
  // Validate origin first for security
  if (event.origin !== "https://your-iframe-domain.com") return;

  switch(event.data.type) {
    case "save":
      // Split combined string into individual saves
      const individualSaves = event.data.payload.split("###");
      // Parse each save back to a usable object
      const parsedSaves = individualSaves.map(save => JSON.parse(save));
      // Now you have an array of save objects to store/manage
      console.log("Loaded saves:", parsedSaves);
      break;
    case "load":
      // For load requests: Send the combined saves back to the iframe
      window.frames[0].postMessage({
        type: "load",
        payload: combinedSaves
      }, "https://your-iframe-domain.com");
      break;
    case "score":
      // Handle score updates as usual
      console.log("Current game score:", event.data.score);
      break;
  }
});

5. Manage Multi-Save Actions

  • Add a new save: Fetch the existing combined string, split it, append the new stringified save, then concat everything back together.
  • Delete a save: Split the combined string, filter out the unwanted save slot, then concat the remaining saves into a new string.

Critical Security Reminder

Never use * as the target origin in postMessage—always specify the exact domain you're communicating with. This prevents malicious scripts from intercepting your game data.


内容的提问来源于stack exchange,提问作者Grak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:26:03