Package | Top Level |
Class | public dynamic class SharedObject |
Inheritance | SharedObject Object |
Player version: | Flash Player 6 |
Here are some common ways to use shared objects:
SharedObject.getLocal()
to create a shared object, such as a calculator with memory. Because the shared object is locally persistent, Flash Player saves its data attributes on the user’s machine when the application ends. The next time the application runs, the calculator contains the values it had when the application ended. Alternatively, if you set the shared object’s data properties to null before the application ends, the calculator opens without any prior values the next time the application runs. SharedObject.getRemote()
to create a remote shared object, such as a phone list, that is persistent on the server. Whenever a client makes any changes to the shared object, the revised data is available to all clients that are currently connected to the object or that later connect to it. If the object is also persistent locally and a client changes the data while not connected to the server, the changes are copied to the remote shared object the next time the client connects to the object. For information about using remote shared objects, see the Flash Media Server documentation. The following discussion describes the use of local shared objects.
Here are three possible uses of local 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.
Adobe 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()
:
SharedObject.getLocal()
— This method returns null
when the user has disabled third-party shared objects and the domain of your SWF file does not match the domain in the browser address bar.
SharedObject.flush()
— This method returns false
when the user has disabled shared objects for your domain or for all domains. It returns "pending"
when additional storage space is needed and the user must interactively decide whether to allow an increase.
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
Property | ||
---|---|---|
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 |
Method | ||
---|---|---|
clear():Void
Purges all the data from the shared object and deletes the shared object from the disk.
|
||
close():Void
Closes the connection between a remote shared object and Flash Media Server.
|
||
Connects to a remote shared object on Flash Media Server through the specified connection.
|
||
Immediately writes a locally persistent shared object to a local file.
|
||
[static]Returns a reference to a locally persistent shared object that is available only to the current client.
|
||
[static]Returns a reference to an object that can be shared across multiple clients using Flash Media Server.
|
||
Gets the current size of the shared object, in bytes.
|
||
Broadcasts a message to all clients connected to a shared object, including the client that sent the message.
|
||
Specifies the number of times per second that a client's changes to a shared object are sent to the server.
|
Methods inherited from class Object | |
---|---|
addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch |
Event | Summary | Defined by | ||
---|---|---|---|---|
Invoked every time an error, warning, or informational note is posted for a shared object. | SharedObject | |||
Invoked when the client and server copies of a remote shared object are synchronized. | SharedObject |
data | property |
public var 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]
See also
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(); };
clear | () | method |
public function 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.
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():
close | () | method |
public function close():Void
Language version: | ActionScript 2.0 |
Player version: | Flash Player 6 |
Closes the connection between a remote shared object and Flash Media Server. If a remote shared object is locally persistent, the user can make changes to the local copy of the object after this method is called. Any changes made to the local object are sent to the server the next time the user connects to the remote shared object.
See also
connect | () | method |
public function connect(myConnection:NetConnection):Boolean
Language version: | ActionScript 2.0 |
Player version: | Flash Player 6 |
Connects to a remote shared object on Flash Media Server through the specified connection. Use this method after calling SharedObject.getRemote()
. After a successful connection, this method returns true
and invokes the SharedObject.onSync()
event handler.
myConnection:NetConnection |
Boolean —
A Boolean value of true if the connection was successfully completed; otherwise, false .
|
See also
flush | () | method |
public function 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.
ParametersminDiskSpace:Number [optional] — An integer specifying the number of bytes that must be allotted for this object. The default value is 0. |
Object —
A Boolean value: true or false ; or a string value of "pending" , as described in the following list:
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. |
See also
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); };
getLocal | () | method |
public static function 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 related to security, see the following:
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 your SWF file is delivered over a non-HTTPS connection and you try to set this parameter to The following diagram shows the use of the |
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 |
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"; }
getRemote | () | method |
public static function getRemote(name:String, remotePath:String, [persistence:Object], [secure:Boolean]):SharedObject
Language version: | ActionScript 2.0 |
Player version: | Flash Player 6 |
Returns a reference to an object that can be shared across multiple clients using Flash Media Server. To create a shared object that is available only to the current client, use SharedObject.getLocal()
. After issuing this command, use SharedObject.connect()
to connect the remote object to Flash Media Server.
To confirm that the local and remote copies of the shared object are in sync, use the SharedObject.onSync()
event handler.
All clients that want to share this object must pass the same values for the name
and remotePath
parameters.
For more information about persistence and naming conventions doe remote shared objects, see the Flash Media Server documentation.
Parametersname:String — The name of the remote shared 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: ~ % & \ ; : " ' , < > ? # |
|
remotePath:String — The URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object to which the shared object will be connected. The default is null. |
|
persistence:Object [optional] — Specifies whether the attributes of the shared object’s data property are persistent locally, remotely, or both. May specify where the shared object will be stored locally. Acceptable values are:
|
|
secure:Boolean [optional] — (Flash Player 8 and later) Determines whether access to this shared object is restricted to SWF files delivered over an HTTPS connection. Assuming that your SWF file is delivered over HTTPS, if this parameter is set to true , only SWF files that are delivered over HTTPS can create or access your SWF's shared objects; if set to false , non-HTTPS connections may access your SWF's shared objects. If your SWF runs on 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. The default value is false . |
SharedObject —
A reference to an object that can be shared across multiple clients. If Flash Player can’t create or find the shared object, returns null.
|
See also
getSize | () | method |
public function 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.
ReturnsNumber —
A numeric value specifying the size of the shared object, in bytes.
|
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);
send | () | method |
public function send(handlerName:String, [optionalArgs:]):Void
Language version: | ActionScript 2.0 |
Player version: | Flash Player 6 |
Broadcasts a message to all clients connected to a shared object, including the client that sent the message. To process and respond to the message, create a function named handlerName
attached to the shared object.
handlerName:String — The handler that processes the message. |
|
optionalArgs: [optional] — The arguments to the handler. They can be of any type. They are serialized and sent over the connection. The receiving handler receives them in the same order as they are sent. If a parameter is a circular object (for example, a circular linked list), the serializer handles the references correctly. |
setFps | () | method |
public function setFps(updatesPerSecond:Number):Boolean
Language version: | ActionScript 2.0 |
Player version: | Flash Player 6 |
Specifies the number of times per second that a client's changes to a shared object are sent to the server. Use this method when you want to control the amount of traffic between the client and the server. For example, if the connection between the client and server is relatively slow, you may want to set updatesPerSecond
to a relatively low value. Conversely, if the client is connected to a multiuser game in which timing is important, you may want to set updatesPerSecond
to a relatively high value.
To manually control when updates are sent, issue this command with updatesPerSecond
set to 0 when you want to send changes to the server.
Regardless of the value that you pass, changes are not sent to the server until SharedObject.onSync()
has returned a value for the previous update. If the response time from the server is slow, updates may be sent to the server less frequently than the value specified in updatesPerSecond
.
updatesPerSecond:Number — A number that specifies how often a client's changes to a remote shared object are sent to the server. The default value is the frame rate of the SWF file. To send changes immediately and then stop sending changes, pass 0. To reset to its default value, pass a value less than 0. |
Boolean —
true if the update was accepted; otherwise, false
|
See also
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). |
infoObject:Object — A parameter defined according to the status message. |
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
onSync | event handler |
public onSync = function(objArray:Array) {}
Language version: | ActionScript 2.0 |
Player version: | Flash Player 6 |
Invoked when the client and server copies of a remote shared object are synchronized. This occurs after a successful call to SharedObject.connect()
or whenever any properties of a shared object change.
This event handler is used with remote shared objects and a server such as Adobe Flash Media Server.
For details, see the Flash Media Server documentation.
ParametersobjArray:Array — An array that contains an information object for every property that has changed. Each information object has the following properties:code, name, oldValue. See the Flash Media Server documentation for details about these codes. |
See also