Home > 梅原 > FlashでCookieの読み書き

FlashでCookieの読み書き

20090617
Category:梅原 /Tags:

cookieFlashからブラウザのCookieって読み書きする方法。
ASからCookieを直接読み書きはできないので、JSを経由することになる。Cookieを読み書きするJSをつくり、AS側からはExternalInterface.callを使って、値を取得する。
ブラウザの差異はJS側で吸収して、AS側は整えられた値を扱うのみとするのがいいだろう。

今回は、ブラウザの差異を吸収し整える部分はCookie Managerというjsのライブラリを使った。AS側はAS3を使ったが、AS2でも基本的にほぼ同じ流れで動くはずだ。

ブラウザが表示する際SWFとJSの動き出すタイミングが異なる(JSのほうが先に実行処理をする)ので、ExternalInterface.addcallbackを使うより、SWF側の準備が整ってから、ExternalInterface.callを実行し、返り値としてCookieの値を受け取る方が、間違いが無いだろう。

**IEでの動作不良が確認されたため、現在cookieの読み書き機能を停止しています。**


Get Adobe Flash player

**IEでの動作不良が確認されたため、現在cookieの読み書き機能を停止しています。**

◆参考
JavaScriptでクッキーを超簡単に使うライブラリ「Cookie Manager」
http://phpspot.org/blog/archives/2006/11/javascriptcooki.html
クッキーを使う方法 – JavaScript
http://www5e.biglobe.ne.jp/~access_r/hp/javascript/js_007.html

◆サンプルファイル、ソースコード
サンプルファイル一式
http://www.mztm.jp/wp/wp-content/uploads/2009/06/umhr_cookie.zip

▼ ActionScript3

package {
	import flash.display.Sprite;
	import flash.net.SharedObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.display.SimpleButton;
	import flash.external.ExternalInterface;
	[SWF(backgroundColor="0xEEEEEE")]
	public class Main extends Sprite {
		private var tf:TextField = Create.newTextField([8,8,stage.stageWidth-16,100],[["border",true],["wordWrap",true]]);
		private var del:SimpleButton = Create.newSimpleButton([8,120,150,24,"クッキーを削除する"]);
		private var sb:SimpleButton = Create.newSimpleButton([stage.stageWidth-158,120,150,24,"クッキーに書き込む"]);
		private var explanation:TextField = Create.newTextField([0,stage.stageHeight-280,stage.stageWidth,280],[["wordWrap",true]]);
		private	var date:Date = new Date();

		//この関数がまず実行される。
		public function Main() {

			var prevDate:String = ExternalInterface.call("getCookie","date");
			if(prevDate){
				tf.appendText("お使いのブラウザからの"+ExternalInterface.call("getCookie","counter")+"回目のアクセスです。\n記録に残っている時刻は"+prevDate+"です。");
			}else{
				tf.text = "ようこそ。お使いのブラウザからの"+ExternalInterface.call("getCookie","counter")+"回目のアクセスです。\n時刻の記録はありません。";
			}
			tf.appendText("\n\n下の「クッキーに書き込む」ボタンをクリックすると今回のアクセス時刻("+date+")を記録します。");

			addChild(tf);
			addChild(del);
			addChild(sb);

			explanation.appendText("HTTP cookie");
			explanation.appendText("\nHTTP cookie(エイチティーティーピークッキー、単にCookieとも表記される)は、RFC 2965などで定義されたHTTPにおけるWebサーバとウェブブラウザ間で状態を管理するプロトコル、またそこで用いられるWebブラウザに保存された情報のことを指す。ユーザ識別やセッション管理を実現する目的などに利用される。");
			explanation.appendText("\n\n出典: フリー百科事典『ウィキペディア(Wikipedia)』\nhttp://ja.wikipedia.org/wiki/HTTP_cookie");
			addChild(explanation);
			sb.addEventListener(MouseEvent.MOUSE_DOWN, MOUSE_DOWN);
			del.addEventListener(MouseEvent.MOUSE_DOWN, delMOUSE_DOWN);
		}

		private function MOUSE_DOWN(e:MouseEvent):void{
			ExternalInterface.call("setCookie",String(date));
			tf.appendText("\nクッキーへの書き込みをしました。");
		}
		private function delMOUSE_DOWN(e:MouseEvent):void{
			ExternalInterface.call("clearCookie");
			tf.text = "クッキーを削除しました。";
		}
	}
}

import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.display.Sprite;
import flash.display.Shape;
import flash.display.SimpleButton;
class Create{
  public static var defaultTextFormat:TextFormat = new TextFormat();

	public static function newSimpleButton(x_y_w_h_txt:Array = null,property:Array=null,graphics:Array=null):SimpleButton{
			var upState:Sprite = newSprite([x_y_w_h_txt[0],x_y_w_h_txt[1]],null,[["beginFill",[0xCCCCCC,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2],x_y_w_h_txt[3],8]]]);
			upState.addChild(newShape([2,2],null,[["beginFill",[0xE5E5E5,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2]-4,x_y_w_h_txt[3]-4,6]]]))
			var overState:Sprite = newSprite([x_y_w_h_txt[0],x_y_w_h_txt[1]],null,[["beginFill",[0xBBBBBB,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2],x_y_w_h_txt[3],8]]]);
			overState.addChild(newShape([2,2],null,[["beginFill",[0xEEEEEE,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2]-4,x_y_w_h_txt[3]-4,6]]]))
			var downState:Sprite = newSprite([x_y_w_h_txt[0],x_y_w_h_txt[1]],null,[["beginFill",[0xAAAAAA,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2],x_y_w_h_txt[3],8]]]);
			downState.addChild(newShape([2,2],null,[["beginFill",[0xDDDDDD,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2]-4,x_y_w_h_txt[3]-4,6]]]))
			var hitTestState:Shape = newShape([x_y_w_h_txt[0],x_y_w_h_txt[1]],null,[["beginFill",[0,1]],["drawRoundRect",[0,0,x_y_w_h_txt[2],x_y_w_h_txt[3],8]]]);
			if(x_y_w_h_txt[4]){
				upState.addChild(newTextField([0,2,x_y_w_h_txt[2],x_y_w_h_txt[3]-2],[["defaultTextFormat",new TextFormat("_sans", null, null, null, null, null, null, null, "center")],["text",x_y_w_h_txt[4]]]));
				overState.addChild(newTextField([0,2,x_y_w_h_txt[2],x_y_w_h_txt[3]-2],[["defaultTextFormat",new TextFormat("_sans", null, null, null, null, null, null, null, "center")],["text",x_y_w_h_txt[4]]]));
				downState.addChild(newTextField([0,3,x_y_w_h_txt[2],x_y_w_h_txt[3]-3],[["defaultTextFormat",new TextFormat("_sans", null, null, null, null, null, null, null, "center")],["text",x_y_w_h_txt[4]]]));
			}
     		var sb:SimpleButton = new SimpleButton(upState,overState,downState,hitTestState);

		return sb;
	}

  public static function newShape(x_y_w_h_sh:Array = null,property:Array=null,graphics:Array=null):Shape{
    var i:int;
    var sh:Shape;
    if(x_y_w_h_sh && x_y_w_h_sh[4]){
      sh = x_y_w_h_sh[4];
    }else{
      sh = new Shape();
    }
    if(x_y_w_h_sh){
      if (x_y_w_h_sh[0]) { sh.x = x_y_w_h_sh[0] };
      if (x_y_w_h_sh[1]) { sh.y = x_y_w_h_sh[1] };
    }
    if(property){
      for (i = 0; i < property.length; i++) {
        if(property[i] && property[i].length > 1){
          sh[property[i][0]] = property[i][1];
        }
      }
    }
    if(graphics){
      for (i = 0; i < graphics.length; i++) {
        if(graphics[i] && graphics[i].length > 1){
          sh.graphics[graphics[i][0]].apply(null, graphics[i][1]);
        }
      }

    }
    if(x_y_w_h_sh){
      if (x_y_w_h_sh[2]) { sh.width = x_y_w_h_sh[2] };
      if (x_y_w_h_sh[3]) { sh.height = x_y_w_h_sh[3] };
    }
    return sh;
  }
  public static function newSprite(x_y_w_h_sp:Array = null,property:Array=null,graphics:Array=null,addChild:DisplayObject = null):Sprite{
    var i:int;
    var sp:Sprite;
    if(x_y_w_h_sp && x_y_w_h_sp[4]){
      sp = x_y_w_h_sp[4];
    }else{
      sp = new Sprite();
    }
    if(x_y_w_h_sp){
      if (x_y_w_h_sp[0]) { sp.x = x_y_w_h_sp[0] };
      if (x_y_w_h_sp[1]) { sp.y = x_y_w_h_sp[1] };
    }
    if(property){
      for (i = 0; i < property.length; i++) {
        if(property[i] && property[i].length > 1){
          sp[property[i][0]] = property[i][1];
        }
      }
    }
    if(graphics){
      for (i = 0; i < graphics.length; i++) {
        if(graphics[i] && graphics[i].length > 1){
          sp.graphics[graphics[i][0]].apply(null, graphics[i][1]);
        }
      }

    }
    if(addChild){
      sp.addChild(addChild);
    }
    if(x_y_w_h_sp){
      if (x_y_w_h_sp[2]) { sp.width = x_y_w_h_sp[2] };
      if (x_y_w_h_sp[3]) { sp.height = x_y_w_h_sp[3] };
    }
    return sp;
  }

  public static function newTextField(x_y_w_h_txt_color_alpha:Array = null,property:Array=null,method:Array=null):TextField{
    var i:int;
    var ta:TextField = new TextField();
    ta.defaultTextFormat = defaultTextFormat;
    if(x_y_w_h_txt_color_alpha){
      if (x_y_w_h_txt_color_alpha[0]) { ta.x = x_y_w_h_txt_color_alpha[0] };
      if (x_y_w_h_txt_color_alpha[1]) { ta.y = x_y_w_h_txt_color_alpha[1] };
      if (x_y_w_h_txt_color_alpha[2]) { ta.width = x_y_w_h_txt_color_alpha[2] };
      if (x_y_w_h_txt_color_alpha[3]) { ta.height = x_y_w_h_txt_color_alpha[3] };
      if (x_y_w_h_txt_color_alpha[4]) { ta.text = x_y_w_h_txt_color_alpha[4] };
      if (x_y_w_h_txt_color_alpha[5]) { ta.textColor = x_y_w_h_txt_color_alpha[5] };
      if (x_y_w_h_txt_color_alpha[6]) { ta.alpha = x_y_w_h_txt_color_alpha[6] };
    }
    if(property){
      for (i = 0; i < property.length; i++) {
        if(property[i] && property[i].length > 1){
          ta[property[i][0]] = property[i][1];
        }
      }
    }
    if(method){
      for (i = 0; i < method.length; i++) {
        if(method[i] && method[i].length > 1){
          ta[i].apply(null, method[i][1]);
        }
      }
    }
    return ta;
  }
}

▼ JavaScript

<script src="http://www.mztm.jp/wp/js/prototype.js" language="javascript"></script>
<script src="http://www.mztm.jp/wp/js/cookiemanager.js" language="javascript"></script>
<script language="javascript">
var manager = new CookieManager({shelfLife:30});
var count = manager.getCookie("counter");
if (count == "") {
	count = 0;
}
count++;
manager.setCookie("counter", count);
var str = manager.getCookie("date");
function getCookie(arg) {
	if(arg == "date"){
		return manager.getCookie("date");
	}else if(arg == "counter"){
		return manager.getCookie("counter");
	}
}
function clearCookie() {
	manager.clearCookie("date");
	manager.clearCookie("counter");
}
function setCookie(arg) {
	manager.setCookie("date", arg);
}
</script>

◆以前作ったサンプル
http://www.mztm.jp/wp/wp-content/uploads/2009/06/070913cookie2swf.zip
FlashPlayer6向け。このバージョンではExternalInterface.callを使えないので、値の書き込みはgetURL(“javascript:setcookie(‘”+setTxt.text+”‘);”);を使い、取得はFlashVarsを使っている。

関連記事:

Comments are closed.