Escaper.as 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Escaper
  3. *
  4. * Escapes all the backslashes which are not translated correctly in the Flash -> JavaScript Interface
  5. *
  6. * Adapted from http://swfupload.googlecode.com/
  7. *
  8. * These functions had to be developed because the ExternalInterface has a bug that simply places the
  9. * value a string in quotes (except for a " which is escaped) in a JavaScript string literal which
  10. * is executed by the browser. These often results in improperly escaped string literals if your
  11. * input string has any backslash characters. For example the string:
  12. * "c:\Program Files\uploadtools\"
  13. * is placed in a string literal (with quotes escaped) and becomes:
  14. * var __flash__temp = "\"c:\Program Files\uploadtools\\"";
  15. * This statement will cause errors when executed by the JavaScript interpreter:
  16. * 1) The first \" is succesfully transformed to a "
  17. * 2) \P is translated to P and the \ is lost
  18. * 3) \u is interpreted as a unicode character and causes an error in IE
  19. * 4) \\ is translated to \
  20. * 5) leaving an unescaped " which causes an error
  21. *
  22. * I fixed this by escaping \ characters in all outgoing strings. The above escaped string becomes:
  23. * var __flash__temp = "\"c:\\Program Files\\uploadtools\\\"";
  24. * which contains the correct string literal.
  25. *
  26. * Note: The "var __flash__temp = " portion of the example is part of the ExternalInterface not part of
  27. * my escaping routine.
  28. */
  29. package
  30. {
  31. public class Escaper
  32. {
  33. public static function escape(message:*):*
  34. {
  35. if (message == null || message is Function) return null;
  36. if (message is String) return escapeString(message);
  37. if (message is Array) return escapeArray(message);
  38. if (message is Boolean || message is Number) return message;
  39. if (message is Date) return message.valueOf();
  40. if (message is Object) return escapeObject(message);
  41. return message;
  42. }
  43. public static function escapeString(message:String):String
  44. {
  45. return message.replace(/\\/g, "\\\\");
  46. }
  47. public static function escapeArray(message_arr:Array):Array
  48. {
  49. var length:int = message_arr.length;
  50. var ret:Array = new Array(length);
  51. for (var i = 0; i < length; i++) {
  52. ret[i] = escape(message_arr[i]);
  53. }
  54. return ret;
  55. }
  56. public static function escapeObject(message_obj:*):Object
  57. {
  58. var ret:Object = { };
  59. for (var name:String in message_obj) {
  60. ret[escapeString(name)] = escape(message_obj[name]);
  61. }
  62. return ret;
  63. }
  64. }
  65. }