Understanding Ruffle Storage Limitations
Ruffle is an open-source Flash Player emulator that runs SWF files in modern web browsers. While it aims for compatibility, its handling of local file I/O operations differs significantly from the original Adobe Flash Player. The original Flash environment used SharedObject instances to store .sol files directly on the user's disk. In the browser context, direct disk access is restricted by security sandbox rules. Consequently, Ruffle’s default attempt to mimic this behavior often fails or behaves inconsistently across different browsers and configurations.
Developers frequently encounter situations where saved games disappear after refreshing the page or where the save dialog never appears. This is not necessarily a bug in your code but a mismatch between legacy Flash expectations and modern web standards. To resolve this, you need to decouple your game logic from the specific .sol file format and instead use web-native storage mechanisms.
Implementing Custom Save Logic
The foundation of any reliable save system in Ruffle is proper data serialization. You cannot simply write raw objects to a file; you must convert them into a string format that can be stored as text. In ActionScript 3, which powers most .swf games, you should use the built-in JSON class if available, or a lightweight library like as3corelib. Avoid non-standard methods like JSON.encode(), as this is not part of the AS3 specification and will cause runtime errors in strict environments.
- Create a Data Model: Define a
classthat holds all variables you wish to persist, such as player health, inventory items, or level progress. - Serialize to String: Use
JSON.stringify(yourData)to convert your object into a single string. Ensure all keys are unique and values are primitive types (strings, numbers, booleans) or nested arrays/objects. - Store in LocalStorage: Access the browser’s
window.localStorageobject through ExternalInterface. Assign your serialized string to a key, such as"game_save_v1".
This method ensures that your data survives page reloads because LocalStorage is designed for exactly this purpose. It is supported by all major browsers that support Ruffle, including Chrome, Firefox, and Safari.
Bridging ActionScript and JavaScript
To interact with LocalStorage, you need a bridge between your SWF content and the HTML page hosting it. Ruffle exposes the ExternalInterface API, allowing ActionScript to call JavaScript functions. You can create a simple wrapper function in your HTML that handles the actual storage operations.
// JavaScript side (in your HTML file)
function saveGameData(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (e) {
console.error("Save failed:", e);
return false;
}
}
function loadGameData(key) {
return localStorage.getItem(key);
}
In your ActionScript code, you then invoke these functions:
// ActionScript side
import flash.external.ExternalInterface;
var dataString:String = JSON.stringify(myGameData);
var success:Boolean = ExternalInterface.call("saveGameData", "my_save_key", dataString);
if (success) {
trace("Game saved successfully.");
} else {
trace("Failed to save game.");
}
This separation of concerns keeps your game logic clean and leverages the browser’s native capabilities. It also makes debugging easier, as you can inspect the LocalStorage entries directly in your browser’s developer tools under the Application tab.
Loading and Deserializing Data
Saving is only half the equation; loading the data back into the game state is equally critical. When the game initializes, check for existing save data before proceeding to the main menu. Retrieve the string from LocalStorage and parse it back into an object structure.
// ActionScript side
var savedJson:String = ExternalInterface.call("loadGameData", "my_save_key");
if (savedJson != null && savedJson.length > 0) {
var myGameData:Object = JSON.parse(savedJson);
// Apply loaded values to current game state
playerHealth = Number(myGameData.health);
currentLevel = int(myGameData.level);
}
Always include error handling around JSON.parse(). If the saved data is corrupted or empty, the parser will throw an exception. Wrap this in a try-catch block to ensure your game doesn’t crash on startup. If parsing fails, initialize default values instead of attempting to use malformed data.
Handling Multiple Saves and Backups
For more complex games, you may want to support multiple save slots. You can achieve this by appending a slot identifier to your storage key, such as "save_slot_1" and "save_slot_2". Additionally, consider implementing a backup mechanism. Since LocalStorage has a size limit (typically 5-10MB), large games might exceed this capacity. If you anticipate large data sets, look into Best Way to Handle Remote Storage Without Local Copy to offload data to a server or use IndexedDB for larger capacities.
Another consideration is data integrity. Before overwriting a save slot, you might want to verify that the new data is valid. Write a validation function that checks for required fields and reasonable value ranges. This prevents players from accidentally corrupting their progress due to bugs or exploits.
Frequently Asked Questions
Why does my save disappear after closing the browser?
If your saves vanish, you are likely relying on session-only storage or temporary cookies. Ensure you are using localStorage rather than sessionStorage. LocalStorage persists indefinitely until manually cleared by the user, whereas sessionStorage is deleted when the tab closes.
Can I still use SharedObject in Ruffle?
While Ruffle attempts to support some legacy APIs, SharedObject behavior is inconsistent and often blocked by modern security policies. It is highly recommended to migrate to the LocalStorage + ExternalInterface pattern for reliable results across all platforms.
What is the maximum size for a saved game?
Browser LocalStorage typically allows between 5MB and 10MB per domain. For most 2D games, this is sufficient. If you are storing high-resolution images or extensive logs, you may hit this limit quickly. In such cases, consider compressing your data or using IndexedDB.
How do I clear saved data for testing?
You can clear all saved data by opening your browser’s Developer Tools (F12), navigating to the Application tab, selecting Local Storage, and clicking the trash icon next to your domain. Alternatively, add a debug command in your game to trigger localStorage.clear() via ExternalInterface.
Is this method compatible with mobile browsers?
Yes, both iOS Safari and Android Chrome support LocalStorage and ExternalInterface calls. However, be aware that some mobile browsers may restrict storage quotas more aggressively than desktop versions. Always test your save functionality on actual mobile devices before release.