Top Level

Class SharedObject

Object


public dynamic class SharedObject
extends Object

Player version: Flash Player 6

The SharedObject class is used to read and store limited amounts of data on a user's computer. Shared objects offer real-time data sharing between objects that are persistent on the user's computer. Local shared objects are similar to browser cookies.

Here are three possible uses of shared objects:

Local shared objects maintain local persistence. For example, you can call SharedObject.getLocal() to create a shared object that contains the high score in a game. Because the shared object is locally persistent, Flash saves its data attributes on the user's computer when the game is closed. The next time the game is opened, the high score from the previous session is displayed. Alternatively, you could set the shared object's properties to null before the game is closed. The next time the SWF file runs, the game opens without the previous high score.

To create a local shared object, use the following syntax:

var so:SharedObject = SharedObject.getLocal("userHighScore");
so.data.highScore = new Number();
so.flush();

In the example, the shared object is explicitly flushed, or written to a disk. When an application closes, shared objects are automatically flushed; however, it is shown here to demonstrate the step of writing data to a disk.

Local disk space considerations: Local shared objects can be very useful, but they have some limitations that are important to consider as you design your application. Sometimes your SWF files may not be allowed to write local shared objects, and sometimes the data stored in local shared objects can be deleted without your knowledge. Flash Player users can manage the disk space that is available to individual domains or to all domains. When users lower the amount of disk space available, some local shared objects may be deleted. Flash Player users also have privacy controls that can prevent third-party domains (domains other than the domain in the current browser address bar) from reading or writing local shared objects.

Note: Local content can always write third-party shared objects to disk, even if writing of shared objects to disk by third-party domains is disallowed.

Macromedia recommends that you check for failures that are related to the amount of disk space available and to user privacy controls. Perform these checks when you call getLocal() and flush():

If your SWF file attempts to create or modify local shared objects, make sure that your SWF file is at least 215 pixels wide and at least 138 pixels high (the minimum dimensions for displaying the dialog box that prompts users to increase their local shared object storage limit). If your SWF file is smaller than these dimensions and an increase in the storage limit is required, SharedObject.flush() fails, returning "pending" but then calling your SharedObject.onStatus handler with a result of "SharedObject.Flush.Failed".

See also
SharedObject.getLocal(), SharedObject.flush(), SharedObject.onStatus



Property Summary
data : Object
The collection of attributes assigned to the data property of the object; these attributes can be shared and/or stored.

Properties inherited from class Object
__proto__, __resolve, constructor, prototype


Event Summary
onStatus = function(infoObject:Object) {}
Invoked every time an error, warning, or informational note is posted for a shared object.


Method Summary
clear() : Void
Purges all the data from the shared object and deletes the shared object from the disk.
flush([minDiskSpace:Number]) : Object
Immediately writes a locally persistent shared object to a local file.
static getLocal(name:String, [localPath:String], [secure:Boolean]) : SharedObject
Returns a reference to a locally persistent shared object that is available only to the current client.
getSize() : Number
Gets the current size of the shared object, in bytes.

Methods inherited from class Object
addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch


Property Detail

data Property

public data : Object

Player version: Flash Player 6

The collection of attributes assigned to the data property of the object; these attributes can be shared and/or stored. Each attribute can be an object of any basic ActionScript or JavaScript type—Array, Number, Boolean, and so on. For example, the following lines assign values to various aspects of a shared object:
var items_array:Array = new Array(101, 346, 483);
var currentUserIsAdmin:Boolean = true;
var currentUserName:String = "Ramona";

var my_so:SharedObject = SharedObject.getLocal("superfoo");
my_so.data.itemNumbers = items_array;
my_so.data.adminPrivileges = currentUserIsAdmin;
my_so.data.userName = currentUserName;

for (var prop in my_so.data) {
    trace(prop+": "+my_so.data[prop]);
}

All attributes of a shared object's data property are saved if the object is persistent, and the shared object contains the following information:

userName: Ramona
adminPrivileges: true
itemNumbers: 101,346,483

Note: Do not assign values directly to the data property of a shared object, as in so.data = someValue; Flash ignores these assignments.

To delete attributes for local shared objects, use code such as delete so.data.attributeName; setting an attribute to null or undefined for a local shared object does not delete the attribute.

To create private values for a shared object--values that are available only to the client instance while the object is in use and are not stored with the object when it is closed--create properties that are not named data to store them, as shown in the following example:

var my_so:SharedObject = SharedObject.getLocal("superfoo");
my_so.favoriteColor = "blue";
my_so.favoriteNightClub = "The Bluenote Tavern";
my_so.favoriteSong = "My World is Blue";

for (var prop in my_so) {
    trace(prop+": "+my_so[prop]);
}

The shared object contains the following data:

favoriteSong: My World is Blue
favoriteNightClub: The Bluenote Tavern
favoriteColor: blue
data: [object Object]

Example
The following example saves text from a TextInput component instance to a shared object named my_so (for the complete example, see SharedObject.getLocal()):
// Create a listener object and function for the <enter> event.
var textListener:Object = new Object();
textListener.enter = function(eventObj:Object) {
    my_so.data.myTextSaved = eventObj.target.text;
    my_so.flush();
};

See also
SharedObject#getLocal()


Event Detail

onStatus Event Handler

public onStatus = function(infoObject:Object) {}

Player version: Flash Player 6

Invoked every time an error, warning, or informational note is posted for a shared object. If you want to respond to this event handler, you must create a function to process the information object that is generated by the shared object.

The information object has a code property containing a string that describes the result of the onStatus handler, and a level property containing a string that is either "Status" or "Error".

In addition to this onStatus handler, Flash also provides a super function called System.onStatus. If onStatus is invoked for a particular object and no function is assigned to respond to it, Flash processes a function assigned to System.onStatus, if it exists.

The following events notify you when certain SharedObject activities occur:

Code property Level property Meaning
SharedObject.Flush.Failed Error SharedObject.flush() command that returned "pending" has failed (the user did not allot additional disk space for the shared object when Flash Player showed the Local Storage Settings dialog box).
SharedObject.Flush.Success Status SharedObject.flush() command that returned "pending" has been successfully completed (the user allotted additional disk space for the shared object).

Parameters
infoObject:Object — A parameter defined according to the status message.

Example
The following example displays different messages based on whether the user chooses to allow or deny the SharedObject object instance to write to the disk.
var message_str:String;
this.createTextField("message_txt", this.getNextHighestDepth(), 0, 0, 300, 22);
message_txt.html = true;
this.createTextField("status_txt", this.getNextHighestDepth(), 10, 30, 300, 100);
status_txt.multiline = true;
status_txt.html = true;

var items_array:Array = new Array(101, 346, 483);
var currentUserIsAdmin:Boolean = true;
var currentUserName:String = "Ramona";
var my_so:SharedObject = SharedObject.getLocal("superfoo");
my_so.data.itemNumbers = items_array;
my_so.data.adminPrivileges = currentUserIsAdmin;
my_so.data.userName = currentUserName;

my_so.onStatus = function(infoObject:Object) {
    status_txt.htmlText = "<textformat tabStops='[50]'>";
    for (var i in infoObject) {
        status_txt.htmlText += "<b>"+i+"</b>"+"\t"+infoObject[i];
    }
    status_txt.htmlText += "</textformat>";
};
            
var flushResult = my_so.flush(1000001);
switch (flushResult) {
case 'pending' :
    message_str = "flush is pending, waiting on user interaction.";
    break;
case true :
    message_str = "flush was successful. Requested storage space approved.";
    break;
case false :
    message_str = "flush failed. User denied request for additional storage.";
    break;
}
message_txt.htmlText = "<a href=\"asfunction:System.showSettings,1\
"><u>"+message_str+"</u></a>";

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components DepthManager class instead of the MovieClip.getNextHighestDepth() method.

See also
SharedObject.getLocal(), System.onStatus


Method Detail

clear Method

public clear() : Void

Player version: Flash Player 7

Purges all the data from the shared object and deletes the shared object from the disk. The reference to my_so is still active, and my_so is now empty.

Example
The following example sets data in the shared object, and then empties all of the data from the shared object.
var my_so:SharedObject = SharedObject.getLocal("superfoo");
my_so.data.name = "Hector";
trace("before my_so.clear():");
for (var prop in my_so.data) {
    trace("\t"+prop);
}
trace("");
my_so.clear();
trace("after my_so.clear():");
for (var prop in my_so.data) {
    trace("\t"+prop);
}

This ActionScript displays the following message in the Output panel:This ActionScript writes the following message to the log file:

before my_so.clear():
    name

after my_so.clear():


flush Method

public flush([minDiskSpace:Number]) : Object

Player version: Flash Player 6

Immediately writes a locally persistent shared object to a local file. If you don't use this method, Flash writes the shared object to a file when the shared object session ends—that is, when the SWF file is closed, that is when the shared object is garbage-collected because it no longer has any references to it or you call SharedObject.clear().

If this method returns "pending", Flash Player shows a dialog box asking the user to increase the amount of disk space available to objects from this domain. To allow space for the shared object to grow when it is saved in the future, which avoids return values of "pending", pass a value for minimumDiskSpace. When Flash tries to write the file, it looks for the number of bytes passed to minimumDiskSpace, instead of looking for enough space to save the shared object at its current size.

For example, if you expect a shared object to grow to a maximum size of 500 bytes, even though it might start out much smaller, pass 500 for minimumDiskSpace. If Flash asks the user to allot disk space for the shared object, it asks for 500 bytes. After the user allots the requested amount of space, Flash won't have to ask for more space on future attempts to flush the object (as long as its size doesn't exceed 500 bytes).

After the user responds to the dialog box, this method is called again and returns either true or false; SharedObject.onStatus is also invoked with a code property of SharedObject.Flush.Success or SharedObject.Flush.Failed.

For more information, see "Local disk space considerations" in the SharedObject class overview.

Parameters
minDiskSpace:Number [optional] — An integer specifying the number of bytes that must be allotted for this object. The default value is 0.

Returns
Object — A Boolean value: true or false; or a string value of "pending", as described in the following list:
  • If the user has permitted local information storage for objects from this domain, and the amount of space allotted is sufficient to store the object, this method returns true. (If you have passed a value for minimumDiskSpace, the amount of space allotted must be at least equal to that value for true to be returned).
  • If the user has permitted local information storage for objects from this domain, but the amount of space allotted is not sufficient to store the object, this method returns "pending".
  • If the user has permanently denied local information storage for objects from this domain, or if Flash cannot save the object for any reason, this method returns false.

Note: Local content can always write shared objects from third-party domains (domains other than the domain in the current browser address bar) to disk, even if writing of third-party shared objects to disk is disallowed.

Example
The following function gets a shared object, my_so, and fills writable properties with user-provided settings. Finally, flush() is called to save the settings and allot a minimum of 1000 bytes of disk space.
this.syncSettingsCore = function(soName:String, override:Boolean, settings:Object) {
    var my_so:SharedObject = SharedObject.getLocal(soName, "http://www.mydomain.com/app/sys");
    // settings list index
    var i;
    // For each specified value in settings:
    // If override is true, set the persistent setting to the provided value.
    // If override is false, fetch the persistent setting, unless there
    // isn't one, in which case, set it to the provided value.
    for (i in settings) {
    if (override || (my_so.data[i] == null)) {
        my_so.data[i] = settings[i];
    } else {
        settings[i] = my_so.data[i];
    }
    }
    my_so.flush(1000);
};

See also
SharedObject.clear(), SharedObject.onStatus

getLocal Method

public static getLocal(name:String, [localPath:String], [secure:Boolean]) : SharedObject

Player version: Flash Player 6

Returns a reference to a locally persistent shared object that is available only to the current client. If the shared object does not already exist, this method creates one. This method is a static method of the SharedObject class. To assign the object to a variable, use syntax like the following:

var so:SharedObject = SharedObject.getLocal("savedData")

Note: If the user has selected to never allow local storage for this domain, the object is not saved locally, even if a value for localPath is specified. The exception to this rule is local content. Local content can always write shared objects from third-party domains (domains other than the domain in the current browser address bar) to disk, even if writing of third-party shared objects to disk is disallowed.

To avoid name collisions, Flash looks at the location of the SWF file that is creating the shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a shared object named portfolio, that shared object does not conflict with another object named portfolio that was created by a SWF file at www.yourCompany.com/photoshoot.swf because the SWF files originate from different directories.

Although the localPath parameter is optional, you should give some thought to its use, especially if other SWF files need to access the shared object. If the data in the shared object is specific to one SWF file that will not be moved to another location, then use of the default value makes sense. If other SWF files need access to the shared object, or if the SWF file that creates the shared object will later be moved, then the value of this parameter affects whether any SWF files are able to access the shared object. For example, if you create a shared object with localPath set to the default value of the full path to the SWF file, then no other SWF file can access that shared object. If you later move the original SWF file to another location, then not even that SWF file can access the data already stored in the shared object.

You can reduce the likelihood that you will inadvertently restrict access to a shared object by using the localpath parameter. The most permissive option is to set the localPath parameter to "/", which makes the shared object available to all SWF files in the domain, but increases the likelihood of name collisions with other shared objects in the domain. More restrictive options are available to the extent that you can append the localPath parameter with folder names that are contained in the full path to the SWF file; for example, your localPath parameter options for the portfolio shared object created by the SWF file at www.myCompany.com/apps/stockwatcher.swf are: "/"; "/apps"; and "/apps/stockwatcher.swf". You need to determine which option provides optimal flexibility for your application.

When using this method, consider the Flash Player security model:

If you publish SWF file content to be played back as local files (either locally installed SWF files or projectors [EXE]), and you need to access a specific shared object from more than one local SWF file, be aware that for local files, two different locations may be used to store shared objects. The domain that is used depends on the security permissions granted to the local file that created the shared object. Local files can have three different levels of permissions: 1) access to the local filesystem only, 2) access to the network only, or 3) access to both the network and the local filesystem. Local files with access to the local filesystem (either 1 or 3) store their shared objects in one location. Local files with no access to the local filesystem (2) store their shared objects in another location. For more information, see the following:

Parameters
name:String — A string that represents the name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:
   ~ % & \ ; : " ' , < > ? # 
   
localPath:String [optional] — A string that specifies the full or partial path to the SWF file that created the shared object, and that determines where the shared object is stored locally. The default value is the full path.
secure:Boolean [optional] — (Flash Player 8 only) Determines whether access to this shared object is restricted to SWF files that are delivered over an HTTPS connection. Assuming that your SWF file is delivered over HTTPS:
  • If this parameter is set to true, Flash Player creates a new secure shared object or gets a reference to an existing secure shared object. This secure shared object can be read from or written to only by SWF files delivered over HTTPS that call SharedObject.getLocal() with the secure parameter set to true.
  • If this parameter is set to false, Flash Player creates a new shared object or gets a reference to an existing shared object. This shared object can be read from or written to by SWF files delivered over non-HTTPS connections.

If your SWF file is delivered over a non-HTTPS connection and you try to set this parameter to true, the creation of a new shared object (or the access of a previously created secure shared object) fails and null is returned. Regardless of the value of this parameter, the created shared objects count toward the total amount of disk space allowed for a domain. The default value is false.

The following diagram shows the use of the secure parameter:

Returns
SharedObject — A reference to a shared object that is persistent locally and is available only to the current client. If Flash Player can't create or find the shared object (for example, if localPath was specified but no such directory exists, or if the secure parameter is used incorrectly) this method returns null.

This method fails and returns null if persistent shared object creation and storage by third-party Flash content is prohibited (does not apply to local content). Users can prohibit third-party persistent shared objects on the Global Storage Settings panel of the Settings Manager, located at http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager03.html.

Example
The following example creates a shared object that stores text that is typed into a TextInput component instance. The resulting SWF file loads the saved text from the shared object when it starts playing. Every time the user presses Enter, the text in the text field is written to the shared object. To use this example, drag a TextInput component onto the Stage, and name the instance myText_ti. Copy the following code into the main Timeline (click in an empty area of the Stage or press Escape to remove focus from the component):
// Create the shared object and set localpath to server root.
var my_so:SharedObject = SharedObject.getLocal("savedText", "/");
// Load saved text from the shared object into the myText_ti TextInput component.
myText_ti.text = my_so.data.myTextSaved;
// Assign an empty string to myText_ti if the shared object is undefined
// to prevent the text input box from displaying "undefined" when
// this script is first run.
if (myText_ti.text == undefined) {
    myText_ti.text = "";
}
// Create a listener object and function for <enter> event
var textListener:Object = new Object();
textListener.enter = function(eventObj:Object) {
    my_so.data.myTextSaved = eventObj.target.text;
    my_so.flush();
};
// Register the listener with the TextInput component instance
myText_ti.addEventListener("enter", textListener);

The following example saves the last frame that a user entered to a local shared object kookie:

// Get the kookie
var my_so:SharedObject = SharedObject.getLocal("kookie");

// Get the user of the kookie and go to the frame number saved for this user.
if (my_so.data.user != undefined) {
    this.user = my_so.data.user;
    this.gotoAndStop(my_so.data.frame);
}

The following code block is placed on each SWF file frame:

// On each frame, call the rememberme function to save the frame number.
function rememberme() {
    my_so.data.frame=this._currentframe;
    my_so.data.user="John";
}


getSize Method

public getSize() : Number

Player version: Flash Player 6

Gets the current size of the shared object, in bytes.

Flash calculates the size of a shared object by stepping through all of its data properties; the more data properties the object has, the longer it takes to estimate its size. Estimating object size can take significant processing time, so you may want to avoid using this method unless you have a specific need for it.

Returns
Number — A numeric value specifying the size of the shared object, in bytes.

Example
The following example gets the size of the shared object my_so:
var items_array:Array = new Array(101, 346, 483);
var currentUserIsAdmin:Boolean = true;
var currentUserName:String = "Ramona";

var my_so:SharedObject = SharedObject.getLocal("superfoo");
my_so.data.itemNumbers = items_array;
my_so.data.adminPrivileges = currentUserIsAdmin;
my_so.data.userName = currentUserName;

var soSize:Number = my_so.getSize();
trace(soSize);