如何基于用户输入动态生成不同postMessage回复并实现多存档功能
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

