Pay attention to the details when passing parameter values from javascript to flash swf files

Source: Internet
Author: User

Q: How to use javascript to pass parameters to SWF files?
I found a complete tutorial on the Internet, which is very enlightening and practical. The following describes the complete implementation steps:
Configure SwfObject:
Swfobject2 is the best method for detecting whether users install Flash. It is considered an 'industry standard', and all new versions of Adobe products (Flex4, Flash CS5) Use SwfObject to detect Flash Player.
Download, decompress the ZIP file, and copy the swfobject. js file to your web server. It is a good idea to create a root folder named 'js' under the root directory. (So the file location should be http://myserver.com/js/swfobject.js ). We will refer to this file in the HTML file created later. If you want to use the expressinstallfunction (for the user to perform a simple upgrade, copy expressinstall.swf to the same folder.
Configure HTML files:
The HTML file contains two Javascript files. A parameter used to capture the source URL. This was created by Matt White, which is simple but effective. The Code is as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
/* Get URL Parameter in Javascript. Code from: http://mattwhite.me/11tmr.nsf/D6Plinks/MWHE-695L9Z */
Function getURLParam (strParamName ){
Var strReturn = "";
Var strHref = window. location. href;
If (strHref. indexOf ("? ")>-1 ){
Var strQueryString = strHref. substr (strHref. indexOf ("? "));
Var aQueryString = strQueryString. split ("&");
For (var iParam = 0; iParam <aQueryString. length; iParam ++ ){
If (aQueryString [iParam]. indexOf (strParamName. toLowerCase () + "=")>-1 ){
Var aParam = aQueryString [iParam]. split ("= ");
StrReturn = aParam [1];
Break;
}
}
}
Return unescape (strReturn );
}
</Script>

Place the above Code in the HEAD tag of your HTML file. You also need to import the SWFObject script. The Code is as follows:
<Script type = "text/javascript" src = "/js/swfobject. js"> </script> another Javascript is to use SwfObject to insert a SWF file. You can place it anywhere in the HTML file. The first thing we need to do is create a DIV tag and prompt the user when the appropriate Flash Player is not installed.
Copy codeThe Code is as follows:
<Div id = "flashcontent">
<Strong> This content requires Flash Player 9 (or a more recent version ).
<Noscript> Make sure JavaScript is turned on. </noscript>
You need to <a href = "http://www.adobe.com/shockwave/download/index.cgi? P1_prod_version = shockwaveflash "target =" _ blank ">
<Span style = "text-decoration: underline;"> upgrade your Flash Player </span> </a> </strong>
</Div>

You can enter any content you want in the DIV label. Add images or feedback as you like, because the content will be replaced by the SWF file.
The following is the Javascript code that implements the replacement function:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var flashvars = {test: getURLParam ("test ")};
Var params = {};
Var attributes = {};
Swfobject. embedSWF ("/articlefiles/jsvars/jsvars.swf", "flashcontent", "550", "400", "9.0.0", "", flashvars, params, attributes );
</Script>

Note that the second line calls the Javascript function 'geturlparam', which has been inserted into the HTML file. The name we passed is exactly the parameter name we want to capture from the URL.
Create a Flash file
Next, create a Flash file. Add a text box to the stage. In the Property panel, set it to 'dynamic text' and the Instance name is 'mytextfield '. You can click 'show text border 'to display borders when selecting a text box.
The following try/catch statement is required to capture passed parameters:
Copy codeThe Code is as follows:
Try {
Var key: String; // This will contain the name of the parameter
Var val: String; // This will contain the value of the parameter
Var flashvars: Object = LoaderInfo (this. root. loaderInfo). parameters;
For (key in flashvars ){
Val = String (flashvars [key]);
MytextField. text = key + ":" + val;
}
} Catch (error: Error ){
// What to do if an error occurs
}

File: jsvars_test.fla
Upload the file along with the HTML file to the server. When running the file, you will see the 'test: 'text box.
Note: If the SWF cannot be displayed, you can only see the word 'upgrade Flash player', which indicates that something is missing on the server. Make sure that you have uploaded the SwfObject file (swfobject. js) to http://myserver.com/js/swfobject.js. Make sure that the SwfObject and SWF file paths in the HTML file are correct. If the problem persists, check the source file and path of the example.
Next, try to add the test parameter http://www.flashmagazine.com/articlefiles/jsvars/jsvars_test.html like this? Test = something. If everything is normal, you will see 'test: something ', indicating that you have successfully passed the parameter to the Flash file.
Further steps
You can also set parameters from SWF files. Http://www.flashmagazine.com/articlefiles/jsvars/jsvars.html in this example? Test = something & id = someID we also implement the sending parameters.
The FLA file contains two text boxes named 'variablesreceived 'and 'variablestosend' respectively, and a button used to send new parameters. In this example, the HTMl file is set to receive the 'test' and 'id' parameters. First, we add some descriptive text to the first text box:
VariablesReceived. text = "Variables passed in:" + ""; then the receiving variable is:
Copy codeThe Code is as follows:
Try {
Var key: String;
Var val: String;
Var flashvars: Object = LoaderInfo (this. root. loaderInfo). parameters;
For (key in flashvars ){
Val = String (flashvars [key]);
VariablesReceived. appendText ("\ t" + key + ":" + val + "");
}
} Catch (error: Error ){
VariablesReceived. appendText (error. toString ());
}

This will list all flashvars In the first text box. Another major function we use in this file is to send the variable function:
Copy codeThe Code is as follows:
// Sending parameters
Function sendVariables (e: MouseEvent): void {
// First we grab the URL of the HTML document and split it into an array
Var htmlUrl: String = ExternalInterface. call ("window. location. href. toString ");
// Split the string at the questionmark
Var splitUrl: Array = htmlUrl. split ("? ");
// Use only the first part (ditch existing parameters)
Var trimmedUrl: String = splitUrl [0];
// Get the parameters we want to append to the URL
Var parameters: String = variablesToSend. text;
// Combine url and parameters with a new questionmark
Var requester: URLRequest = new URLRequest (trimmedUrl + "? "+ Parameters );
// Reload the page
NavigateToURL (requester, '_ self ');
}

Here we use a little trick to capture the URL of the HTML text inserted in the SWF file by using 'externalinterface. call. Flash files only point to their own URLs. This technique breaks through this restriction. ExternalInterface is opened by default in SwfObject, but you can disable it manually.

We do not need parameters (that is '...? Test = something & id = 5 ′). Therefore, we only keep the part before the question mark and store it in the 'trimmedurl' variable for future use. We capture the parameters in the 'variablestosend' text box and pass them to URLRequest. By passing the request to 'navigatetourl', the browser reloads the HTML page and displays the recently submitted value pairs in the 'variablesreceived' text box.

Note: you cannot test it in Flash. You need to upload the file to the server, because both FlashVars and ExternalInterface need SWF to be inserted into the browser.

Finally, we must use addEventListener to call the 'sendariables 'method for the sending button settings.
SendButton. addEventListener (MouseEvent. CLICK, sendVariables); now you know how to use Javascript to pass parameters to each other. Let's use what we have learned to do something useful.

Navigation to create record status
Before the end, let's build a small menu system, which can highlight the current click button, you can download the completed file or run the case, let's take a look at the Code:
First, stop playing the SWF timeline and set the event listener for mouse clicks.
Stop ();
// Setup our 5 buttons
Item1.addEventListener (MouseEvent. CLICK, gotoURL );
Item2.addEventListener (MouseEvent. CLICK, gotoURL );
Item3.addEventListener (MouseEvent. CLICK, gotoURL );
Item4.addEventListener (MouseEvent. CLICK, gotoURL );
Item5.addEventListener (MouseEvent. CLICK, gotoURL); When a button is still clicked, they will execute the 'gotourl' function. Next, we capture parameters from the URL:
Copy codeThe Code is as follows:
// Grab variables
Try {
Var key: String;
Var val: String;
Var flashvars: Object = LoaderInfo (this. root. loaderInfo). parameters;
For (key in flashvars ){
Val = String (flashvars [key]);
If (key = "item") {// If the parameter is called 'item '...
If (val. substr (0, 4) = "item") {//... and the name of the button starts with the characters 'item '...
//... We can extract the number-part of the item-name and go to the correct frame
Var frameToGoTo: Number = Number (val. substr (4, 1 ));
GotoAndStop (frameToGoTo + 1 );
}
}
}
} Catch (error: Error ){
// What to do if an error occurs
}

As you can see, this is very similar to the previous practice. However, the parameter name we passed this time is 'item '. This parameter is the name of the button we click.
Next is the gotoURL function.
Copy codeThe Code is as follows:
// Get the new page
Function gotoURL (e: MouseEvent): void {
// First we grab the URL of the HTML document and split it into an array
Var htmlUrl: String = ExternalInterface. call ("window. location. href. toString ");
// Split the string at the questionmark
Var splitUrl: Array = htmlUrl. split ("? ");
// Use only the first part (ditch existing parameters)
Var trimmedUrl: String = splitUrl [0];
// Get the name of the button clicked and set it as a parameter
Var parameters: String = "item =" + e. currentTarget. name;
// Combine url and parameters with a new questionmark
Var requester: URLRequest = new URLRequest (trimmedUrl + "? "+ Parameters );
// Reload the page
NavigateToURL (requester, '_ self ');
}

We create our own parameters by associating the 'item = 'character with the name of the clicked button. Then, pass the URL and parameters to the navigateToURL method and reload the HTML page with new parameters.

How events work: when something is clicked, we use the addEventListener () method to listen to click events. events include references to the clicked objects. The 'currenttarget' attribute references the clicked object (e. currentTarget), so that we can use e. currentTarget. name to get its name.

To become a complete menu system, you also need to load a new URL, instead of using the same URL as in the example. Now you should know the most basic knowledge. It can run in multiple ways at the same time. You can store the URL as a variable in SWF, load it from an XML file, or use other methods. So I will give it to you. If you have created a solution using this tutorial, post a URL in the comments so that other learners can see it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.