stringjsonactionscript-3internet-explorerflashvars

Internet Explorer truncating flashVars containing JSON


This only happens in IE.

I'm using swfobject and loading the flash vars as such

var flashVars = {
       myVar:'{"url":"http://google.com/", "id":"9999"}',
};
var params = {
    allowFullScreen:"true",
    wmode:"transparent",
    allowScriptAccess:'always'
    };
swfobject.embedSWF("mySwf.swf", "mySwf", "512", "318", "10.0.0", "./js/swfobject/expressInstall.swf", flashVars, params);

Everything works perfectly in all browser but IE. I checked myVar and it comes into the swf as { and that's it. I know it's dying at the '. I've tried putting a \ infront, then tried \\ and kept adding one slash until I got to \\\\\\\\. I even inverted all the slashes and tried the same ritual. Nothing.

I can get the string to finally come through, with inverted quotes and using double slashes, but then my JSON parser gets mad about there being slashes in my string.

Here's an example of what works, but of what is invalid JSON:

"{\\'url\\':\\'http://google.com/\\', \\'id\\':\\'9999\\'}"

Solution

  • Yep IE treats flashVars differently to all the other major browsers, I believe you need to make use of the JavaScript encodeURIComponent method which will escape all reserved characters from your String, eg:

    // Removing all reserved characters from the flashVar value.
    var flashVars = {
       myVar: encodeURIComponent('{"url":"http://google.com/", "id":"9999"}'),
    };
    

    If you are passing multiple values in the flashVars then you could iterate through them and encode all chars in a single pass:

    var flashVars = {
       myVar: '{"url":"http://google.com/", "id":"9999"}',
       anotherVar: 42
    };
    
    // Escape all values contained in the flashVars object.
    for (key in flashVars) {
        if (flashVars.hasOwnProperty(key)) {
            flashVars[key] = encodeURIComponent(flashVars[key]);
        }
    }
    

    As @dgmdan and @bcmoney suggested, it would probably make your code easier to read if you made use of JSON.stringify - however, you need to bear in mind that IE8 and below do not have a native JSON object, so you will need to include Crockford's JS Library in your HTML page.

    // Making use of a JSON library.
    var flashVars = {
       myVar: encodeURIComponent(JSON.stringify({ url: "http://google.com/", id: "9999"})),
    };
    

    Also, it's worth bearing in mind that flashVars are limited to ~64k; so if you are planning to pass a lot of data, it might be better to use an ExternalInterface call to pull them from the JavaScript instead.