JavaScriptからSWFに変数を渡すには、FlashVarsを使うんだけど、
変数に2バイト文字のデータが含まれていると、文字化けすることがある。
その例が下のサンプル1。
サンプル1 (Javascript)
※文字コードはEUC-JPか、Shift-JIS
<script type="text/javascript">
<!--
var URL = 「SWFへのパス」;
var Width = 200;
var Height = 50;
var MyString = "ほげほげ"; //2バイト文字代入
URL += "?JS_String="+MyString;
document.write("<object type=\"application/x-shockwave-flash\" data=\""+URL
+"\" width=\""+Width+"\" height=\""+Height+"\">");
document.write("<param name=\"movie\" value=\""+URL+"\" />");
document.write("<param name=\"quality\" value=\"high\" />");
document.write("<param name=\"wmode\" value=\"transparent\" />");
document.write("<param name=\"FlashVars\" value=\""+URL+"\" ></object>");
-->
</script>
サンプル1 (AcrionScript)
/* テキストフィールドの作成 */
// _txt TextField
this.createTextField("_txt",300, 5, 5, 190, 40); //インスタンス名,深度,X,Y,幅,高
this._txt.textColor = 0x000000; //色
this._txt.multiline = true; //複数行
var format = new TextFormat();
format.size = 12;
this._txt.setNewTextFormat(format);
this._txt.text = _root.JS_String;
サンプル1 (実行結果)

このように文字化けします。
(IEでは文字化けしません。あと、JavaScriptの文字コードがUTF-8の時も大丈夫)
因みに、ActionScriptの最初に
System.useCodepage = true;
を付け加えても実行結果は同じです。
2バイト文字のまま文字列を渡すことができないので、以下の処理をします。
- JavaScriptで文字列をURLエンコードし、変数に代入する
- JavaScriptからActionScriptに変数を渡す(サンプル1の時と同じ)
- ActionScriptで文字列をデコードする
JavaScriptもActionScriptもエンコーディングの扱いを
Unicodeとしているらしいので、
これでうまくいくはず…?(よくわからん)
これを実装したのが下のサンプル2。
サンプル2(Javascript)
※文字コードはEUC-JPか、Shift-JIS
<script type="text/javascript">
<!--
var URL = 「SWFへのパス」;
var Width = 200;
var Height = 50;
var MyString = "ほげほげ"; //2バイト文字代入
MyString = encodeURI( MyString ); //URLエンコード
URL += "?JS_String="+MyString;
document.write("<object type=\"application/x-shockwave-flash\" data=\""+URL
+"\" width=\""+Width+"\" height=\""+Height+"\">");
document.write("<param name=\"movie\" value=\""+URL+"\" />");
document.write("<param name=\"quality\" value=\"high\" />");
document.write("<param name=\"wmode\" value=\"transparent\" />");
document.write("<param name=\"FlashVars\" value=\""+URL+"\" ></object>");
-->
</script>
サンプル2 (AcrionScript)
/* テキストフィールドの作成 */
// _txt TextField
this.createTextField("_txt",300, 5, 5, 190, 40); //インスタンス名,深度,X,Y,幅,高
this._txt.textColor = 0x000000; //色
this._txt.multiline = true; //複数行
var format = new TextFormat();
format.size = 12;
this._txt.setNewTextFormat(format);
this._txt.text = unescape( _root.JS_String ); //デコード
サンプル2(実行結果)
はい、できたー。
JavaScriptの文字コードはEUC-JP, Shift-JIS, UTF-8の3種類を試したけど、
全部同じ結果だったので、これで大丈夫なはず。
あと、サンプル2の最後のデコードはやらなくても、実行結果は同じになります。
参考サイト
[228618]FlashVars を使用して SWF へ変数を渡す
[228624]Macromedia Flash Player 6 以降でのエンコーディングについて
encodeURI – URLエンコード – JavaScriptリファレンス
文字列をURLエンコード/デコードしたい