FlashからJavaScriptの関数を実行する - Action Script

FlashからJavaScriptの関数を実行します。

UI

下図のUIを作成します。ボタンを1つ配置します。配置後ボタンのClickイベントハンドラを生成します。(ボタンのClickイベントハンドラーの生成の手順はこちらの記事を参照してください。)

コード

Flash部分 (mxmlファイル)

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               width="320" height="160" minWidth="955" minHeight="600">
  
  <fx:Script>
    <![CDATA[
      protected function button1_clickHandler(event:MouseEvent):void
      {
        // TODO Auto-generated method stub
        if (ExternalInterface.available) {
          var wrapperFunction:String = "SampleFunction";
          ExternalInterface.call(wrapperFunction, "Hello Flash World!");
        }
      }
    ]]>
  </fx:Script>
  
  <fx:Declarations>
    <!-- 非ビジュアルエレメント (サービス、値オブジェクトなど) をここに配置 -->
  </fx:Declarations>
  <s:Button x="10" y="10" label="ボタン" click="button1_clickHandler(event)"/>
</s:Application>
解説
if (ExternalInterface.available) {
  ...
}
ExternalInterfaceがサポートされているか確認します。OSとブラウザの組み合わせによっては使用できない場合があります。

var wrapperFunction:String = "SampleFunction";
var s:String = ExternalInterface.call(wrapperFunction, "Hello Flash World!");
ExternalInterface.call()メソッドを用いてJavaScript関数を実行します。最初の引数に実行するJavaScriptの関数名を与えます。第二引数に実行するJavaScript関数の引数を与えます。

HTMLテンプレート (index.template.html)

テンプレートファイルに、JavaScriptの関数を追記します。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
    <!-- 
    Smart developers always View Source. 
    
    This application was built using Adobe Flex, an open source framework
    for building rich Internet applications that get delivered via the
    Flash Player or to desktops via Adobe AIR. 
    
    Learn more about Flex at http://flex.org 
    // -->
    <head>
        <title>${title}</title>
        <meta name="google" value="notranslate" />         
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!-- Include CSS to eliminate any default margins/padding and set the height of the html element and 
             the body element to 100%, because Firefox, or any Gecko based browser, interprets percentage as 
             the percentage of the height of its parent container, which has to be set explicitly.  Fix for
             Firefox 3.6 focus border issues.  Initially, don't display flashContent div so it won't show 
             if JavaScript disabled.
        -->
        <style type="text/css" media="screen"> 
            html, body  { height:100%; }
            body { margin:0; padding:0; overflow:auto; text-align:center; 
                   background-color: ${bgcolor}; }   
            object:focus { outline:none; }
            #flashContent { display:none; }
        </style>
        
        <!-- Enable Browser History by replacing useBrowserHistory tokens with two hyphens -->
        <!-- BEGIN Browser History required section ${useBrowserHistory}>
        <link rel="stylesheet" type="text/css" href="history/history.css" />
        <script type="text/javascript" src="history/history.js"></script>
        <!${useBrowserHistory} END Browser History required section -->  
            
        <script type="text/javascript" src="swfobject.js"></script>
        <script type="text/javascript">
            // For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. 
            var swfVersionStr = "${version_major}.${version_minor}.${version_revision}";
            // To use express install, set to playerProductInstall.swf, otherwise the empty string. 
            var xiSwfUrlStr = "${expressInstallSwf}";
            var flashvars = {};
            var params = {};
            params.quality = "high";
            params.bgcolor = "${bgcolor}";
            params.allowscriptaccess = "sameDomain";
            params.allowfullscreen = "true";
            var attributes = {};
            attributes.id = "${application}";
            attributes.name = "${application}";
            attributes.align = "middle";
            swfobject.embedSWF(
                "${swf}.swf", "flashContent", 
                "${width}", "${height}", 
                swfVersionStr, xiSwfUrlStr, 
                flashvars, params, attributes);
            // JavaScript enabled so display the flashContent div in case it is not replaced with a swf object.
            swfobject.createCSS("#flashContent", "display:block;text-align:left;");
        </script>

        <!-- 追加 -->
        <script type="text/javascript">
          function SampleFunction(message){
            alert("OK : " + message);
          }
        </script>
    </head>
    <body>
        <!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough 
             JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show
             when JavaScript is disabled.
        -->
        <div id="flashContent">
            <p>
                To view this page ensure that Adobe Flash Player version 
                ${version_major}.${version_minor}.${version_revision} or greater is installed. 
            </p>
            <script type="text/javascript"> 
                var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://"); 
                document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='" 
                                + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>" ); 
            </script> 
        </div>
        
        <noscript>
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="${width}" height="${height}" id="${application}">
                <param name="movie" value="${swf}.swf" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="${bgcolor}" />
                <param name="allowScriptAccess" value="sameDomain" />
                <param name="allowFullScreen" value="true" />
                <!--[if !IE]>-->
                <object type="application/x-shockwave-flash" data="${swf}.swf" width="${width}" height="${height}">
                    <param name="quality" value="high" />
                    <param name="bgcolor" value="${bgcolor}" />
                    <param name="allowScriptAccess" value="sameDomain" />
                    <param name="allowFullScreen" value="true" />
                <!--<![endif]-->
                <!--[if gte IE 6]>-->
                    <p> 
                        Either scripts and active content are not permitted to run or Adobe Flash Player version
                        ${version_major}.${version_minor}.${version_revision} or greater is not installed.
                    </p>
                <!--<![endif]-->
                    <a href="http://www.adobe.com/go/getflashplayer">
                        <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
                    </a>
                <!--[if !IE]>-->
                </object>
                <!--<![endif]-->
            </object>
        </noscript>     
   </body>
</html>
解説
SampleFunction()関数を記述します。引数の内容をAlert関数を使って表示する関数です。

実行結果

Flashプロジェクトを実行します。下図の画面が表示されます。ボタンをクリックします。


JavaScript関数が実行されメッセージが表示されました。関数のパラメーターもFlash側から渡されていることがわかります。


引数を受け取る場合

引数を受け取る場合の例です。

UI

下図のUIを準備します。先のUIにラベルを1つ追加します。ラベルのIDをlabel_messageとします。

コード

Flash部分

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               width="320" height="160" minWidth="955" minHeight="600">
  
  <fx:Script>
    <![CDATA[
      protected function button1_clickHandler(event:MouseEvent):void
      {
        // TODO Auto-generated method stub
        if (ExternalInterface.available) {
          var wrapperFunction:String = "SampleFunction";
          var s:String = ExternalInterface.call(wrapperFunction, "Hello Flash World!");
          label_message.text=s;
        }
      }
    ]]>
  </fx:Script>
  
  <fx:Declarations>
    <!-- 非ビジュアルエレメント (サービス、値オブジェクトなど) をここに配置 -->
  </fx:Declarations>
  <s:Button x="10" y="10" label="ボタン" click="button1_clickHandler(event)"/>
  <s:Label id="label_message" x="10" y="39" text="ラベル"/>
</s:Application>
解説
JavaScript関数の戻り値はcallメソッドの戻り値に渡されます。

HTMLテンプレート部

SampleFunction関数を以下に置き換えます。
<script type="text/javascript">
  function SampleFunction(message){
    alert("OK : " + message);
    return "SampleFunction Exec";
  }
</script>
解説
関数の戻り値を返す動作にします。

実行結果

Flashプロジェクトを実行します。下図の画面が表示されます。ボタンを押します。


JavaScript関数が実行され、Alertダイアログが表示されます。OKボタンをしてAlertファイアログを閉じます。


JavaScript関数の戻り値がラベルに表示されます。


このページのキーワード
  • FlashからJSの関数を実行する
著者
iPentecのメインデザイナー
Webページ、Webクリエイティブのデザインを担当。PhotoshopやIllustratorの作業もする。
掲載日: 2012-03-25
iPentec all rights reserverd.