Archive

Posts Tagged ‘cookie’

Flex: ExternalInterface – The Flex Javascript Bridge

August 21st, 2009 No comments

It is really very easy to gain access to Javascript via Flex, the Javascript API is made available via flash.external.ExternalInterface flex class. There are a couple of methods you can use, you can either:

  • Make calls to pre-existing functions (yours or exists JS ones) using the flex ExternalInterface.call function where the argument to call is a string which represents the normal Javascript function invocation.
  • Defined a whole Javascript function inside Flex as a string and pass that string to call, ExternalInterface.call will then automatically execute the function.

There is of course no real use in passing in arguments if you are pre-defining the Javascript function as a string because you can just use those value during the generation of the string.

Below is an example of creating and fetching a Javascript cookie, you never know it might come in handy :)

// ************************ START EXAMPLE *****************************

/**
 * Flex class ExternalInterface does all the magic
 */

import flash.external.ExternalInterface;

public function createCookie(name:String,value:String,days:int=0):void{

    var js:String = "function createCookie(){" +
                     "var expires = '';" +

    "if (" + days + " > 0){" +
        "var date = new Date();" +
        "date.setTime(date.getTime()+(" + days + "*24*60*60*1000));" +
        "expires = 'expires = ' + date.toGMTString();" +
        "}" +
        "document.cookie = '" + name + "=" + value + "; expires=' + expires + '; path=/';" +
    "}";
 
    ExternalInterface.call(js);

}

public function getCookie(cookieName:String):String {

   var r:String = "";

    var search:String = cookieName + "=";
    var js:String = "function getCookie(){return document.cookie;}";
    var cookieVariable:String = ExternalInterface.call(js).toString();

    if (cookieVariable.length > 0) {
        var offset:int = cookieVariable.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            var end:int = cookieVariable.indexOf(";", offset);
            if (end == -1){
                end = cookieVariable.length;
            }
            r = unescape(cookieVariable.substring(offset, end));
        }
    }

    return r;

}

// ************************ END EXAMPLE *****************************