JavaScript passes parameter values to Flash SWF file Note Details _ Basics

Source: Internet
Author: User
Tags event listener
question: How do I pass parameters to the SWF file using JavaScript?
Find a complete tutorial on the Internet, very enlightening and practical, the following is the complete implementation of the steps:
Configure SWFObject
Swfobject2 is the best way to detect if a user is installing flash at the moment. It is considered an ' industry standard ' and a new version of all Adobe Products (Flex4,flash CS5) will use SWFObject to detect Flash Player.
First download, unzip the zip file, copy the Swfobject.js file to your Web server, the root directory to create a "JS" root folder is a good idea. (So the file location should be http://myserver.com/js/swfobject.js). We will refer to this file in the HTML file we created later. If you want to use the Expressinstall feature (provide users with a simple upgrade method), you must copy the expressinstall.swf to the same folder.
Configuring HTML Files
The HTML file consists of two JavaScript. A parameter used to crawl from the URL. This was created by Matt White, which is simple but very effective. The code is as follows:
Copy Code code as follows:

<script type= "Text/javascript" >
/* Get URLs 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 import SWFObject script into the code as follows:
<script type= "Text/javascript" src= "/js/swfobject.js" ></script> another javascript is inserting SWF files using SWFObject. You can place it anywhere in the HTML file. The first thing we need to do is create a div tag that prompts the user when no suitable Flash Player is installed.
Copy Code code 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>
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>

Within the div tag you can enter any content you want to enter. Add pictures or feedback as you like, because the content will be replaced by the SWF file.
Next is the JavaScript that implements the substitution feature:
Copy Code code as follows:

<script type= "Text/javascript" >
var flashvars = {Test:geturlparam ("Test")};
var params = {};
var attributes = {};
swfobject.embedSWF ("/articlefiles/jsvars/jsvars.swf", "flashcontent", "the" "," "," "9.0.0", "", Flashvars, params, attributes);
</script>

Notice the second line, we call the JavaScript function ' Geturlparam ', which has been inserted into the HTML file. The name we are passing is precisely the name of the parameter that you want to capture from the URL.
Create a Flash file
The next step is to create the Flash file. Adds a text box to the stage. Set to ' dynamic text ' in the property panel, with the instance named ' MyTextField '. Display a border when the text box is selected by clicking the ' Show text around border ' implementation.
Capturing the passed in parameters requires the following Try/catch statement:
Copy Code code as follows:

try {
var key:string; This would contain the name of the parameter
var val:string; This is 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 does if an error occurs
}

file: Jsvars_test.fla
Upload files and HTML files to the server. When you run the file, you will see the word ' Test: ' in the text box.
Note: If the SWF cannot be displayed, you only see the word ' Upgrade Flash Player ' stating that there is something missing on the server. Make sure you have uploaded the SWFObject file (swfobject.js) to Http://myserver.com/js/swfobject.js. Also make sure that the SWFObject file and SWF file path in the HTML file are correct. If you still have a problem, look at the source file and path for the example.
Next, try adding the test parameter http://www.flashmagazine.com/articlefiles/jsvars/jsvars_test.html?test=something like this. If everything works, you'll see ' Test:something ' indicates that you have successfully passed the parameters to the Flash file.
Further
You can also set parameters from the SWF file. In this example Http://www.flashmagazine.com/articlefiles/jsvars/jsvars.html?test=something&id=someID we also implement the send parameters.
The FLA file contains two text boxes named ' variablesreceived ' and ' variablestosend ', and a button to send new parameters. This example of the HTML file is set to receive ' Test ' and ' ID ' two parameters. First we add some descriptive text to the first text box:
Variablesreceived.text = "Variables passed in:" + ""; Next you receive the variable:
Copy Code code 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 enumerate all the flashvars in the first text box. Another major function we use in this file is to send variable functions:
Copy Code code as follows:

Sending parameters
function Sendvariables (e:mouseevent): void {
We grab the URL of the HTML document and split it into array
var htmlurl:string = Externalinterface.call ("window.location.href.toString");
Split the string at the Questionmark
var Spliturl:array = Htmlurl.split ("?");
Use only the The "I" (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 by using ' Externalinterface.call ' to capture the URL of the HTML text inserted by the SWF file. The flash file only knows the URL that points to itself, this technique breaks through this limitation. Externalinterface is opened by default in SWFObject, but you can turn it off manually.

We do not need the current URL of the parameters (that is, ' ...? test=something&id=5′). So we just 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 the urlrequest. By passing the request to ' Navigatetourl ', the browser reloads the HTML page and displays the most recently submitted value pairs in the ' variablesreceived ' text box.

Note: You cannot test it in Flash. You need to upload files to the server because both Flashvars and externalinterface require the SWF to be inserted into the browser.

Finally we have to use AddEventListener to call the ' Sendvariables ' method for the Send button settings.
Sendbutton.addeventlistener (mouseevent.click,sendvariables); Now you know how to use JavaScript to pass arguments to each other. Let's do something useful with what we learn.

to create a navigation for record status
Before we finish, let's build a small menu system that highlights the current click button, you can download the completed file or run the case, let's take a look at the code:
First stop the SWF's timeline playback, set the event listener for the mouse click.
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 perform the ' Gotourl ' function. Next, we capture the parameters from the URL:
Copy Code code 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 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 does if an error occurs
}

As you can see, this is very similar to the previous approach. But this time we passed the parameter name ' item '. This parameter is the name of the button we clicked on.
Next is the Gotourl function.
Copy Code code as follows:

Get the new page
function Gotourl (e:mouseevent): void {
We grab the URL of the HTML document and split it into array
var htmlurl:string = Externalinterface.call ("window.location.href.toString");
Split the string at the Questionmark
var Spliturl:array = Htmlurl.split ("?");
Use only the The "I" (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 combining the ' item= ' character and clicking on the button name. The URL and the parameters are then passed to the Navigatetourl method to reload the HTML page with the new parameters.

How events work: When something is clicked we use the AddEventListener () method to listen for the Click event, and the event contains a reference to the object being clicked. The ' Currenttarget ' attribute refers to the object being clicked (E.currenttarget) so that we can use E.currenttarget.name to get its name.

To become a complete menu system, you will also need to make the new URLs loaded instead of using the same URLs as examples. You should now know the most basic knowledge. It can be run in a variety of ways at the same time. You can store URLs as variables in SWF, load from an XML file, or more. So I'll give this to you. If you use this tutorial to create a solution, 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.