How to Use Cross-Domain Shared Objects in Flash

I figured out how to share persistent data across different domains using Shared Objects after doing some poking around in Flash. An ancient article, Flash Shared Object Cross Domain Trick, got me started on the problem. Turns out it's not so difficult.

Diving right in, you have two SWFs: http://serverdomain.tld/server.swf and http://clientdomain.tld/client.swf. The movie server.swf will store the Shared Object and define a couple functions for accessing the shared data. Meanwhile, on the other domain, client.swf will load server.swf into its timeline and make calls to those functions.

// allow cross-scripting from clientdomain.tld
System.security.allowDomain("clientdomain.tld");
 
function setValue(value):Void
{
    var so:SharedObject = SharedObject.getLocal("testSharedData");
    so.data.value = value;
    so.flush();
}
 
function getValue()
{
    var so:SharedObject = SharedObject.getLocal("testSharedData");
    return so.data.value;
}

Most of this is usual Shared Object fare. The functions either retrieve a value or set it and save it to the Shared Object. The important bit here is the very first line, System.security.allowDomain("clientdomain.tld"); which allows client.swf to call these functions.

loadMovie("http://serverdomain.tld/server.swf", "server_mc");
 
function onButtonRelease():Void
{
    // display the current shared value in a text field
    readout_tf.text = server_mc.getValue();
 
    // set the shared value to something else
    var newValue:String = prompt_ti.text;
    server_mc.setValue(newValue);
}

client.swf loads server.swf and gives it the instance name, server_mc. Once server.swf has been completely loaded, its functions getValue and setValue can be called.

Strangely, the cross-domain policy file at http://serverdomain.tld/crossdomain.xml doesn't seem to be necessary. I thought the loadMovie call would fail without it. I even loaded a SWF from wwwimages.adobe.com. What gives?

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a Gravatar account, used to display your avatar.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You can enable syntax highlighting of source code with the following tags: <code>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

About

Daniel McLaren

Daniel is a Flash and Flex developer specializing in the art of information visualization.

Latest from SketchyD

Latest Drawing from SketchyD

This is the most recent drawing from my mobile sketch blog, SketchyD.com.

Recent comments