AJAX - The Complete Reference

(avery) #1

532 Part III: Advanced Topics


ExternalInterface.addCallback("add", null, add);
ExternalInterface.addCallback("get", null, get);
ExternalInterface.addCallback("clear", null, clear);
ExternalInterface.addCallback("remove", null, remove);
ExternalInterface.addCallback("getAll", null, getAll);
}
}

Similar to the previous examples using a Flash bridge, we can call the various methods
in the page directly from JavaScript. First, as before, we have to add the SWF file to the page
and then reference it in browser-specific ways. We omit showing this code again since we
have seen it twice already in this chapter. Then, we return a reference to the embedded
SWF object.

var storageObject = getSWF("flashstorage");

To add a value to Flash’s storage, we simply call the externally exposed add() method,
passing the key and value we are interested in storing.

storageObject.add("timelord", "the doctor");

Retrieving is quite simple as well: just call the external get() method on the embedded
SWF object and pass it the key of interest and it will return a value if there is one.

var val = storageObject.get("timelord");
// returns "the doctor"

To further explorer Flash’s persistence system, we have provided a demo at
http://ajaxref.com/ch10/persistenceflashexplorer.html. You should find it quite interesting
and maybe a tad disturbing that you can reference persisted data between browsers using
this scheme, as demonstrated in Figure 10-11.
The final solution we present is the native storage mechanism found in Firefox 2-and-up
browsers, based upon the WhatWG’s (www.whatwg.org) global persistence object. In
supporting browsers, you can specify the domain where the storage items are available. For
example, globalStorage[""] is available to all domains, while
globalStorage["ajaxref.com"] would be available to all ajaxref.com domains and
globalStorage["www.ajaxref.com"] would just be accessible to that particular domain.
Once you have defined your storage range, you can use getItem(key) and
setItem(key,value)methods on the object like so:

var storageObject = globalStorage("ajaxref.com");
storageObject.setItem("secretagent","007");
var value = storageObject.getItem("secretagent");
// returns "007"

We summarize each of the storage mechanisms discussed so far in Table 10-3.
We’ve implemented each of these mechanisms except the Flash approach in the
AjaxTCR library, with the library failing back to cookies if another approach is unavailable.
The details required to store persistent data regardless of underlying mechanism are as
follows.
Free download pdf