15 October 2008
You should have a basic understanding of the Flash authoring tool, HTML, and JavaScript.
Intermediate
SWFObject 2 offers multiple standards-friendly methods to embed SWF files into web pages. It uses JavaScript to detect Flash Player and avoid broken SWF content, and is designed to make embedding SWFs as easy as possible. It supports the use of alternative content to display content to people that browse the web without plug-ins, to help search engines index your content, or to point visitors to the Flash Player download page. SWFObject 2 detection is future-proof, includes Adobe Express Install, and offers an elaborate API for JavaScript developers. All of this is powered by one small (under 10K) JavaScript file.
No matter if you are an HTML, Flash, or JavaScript developer, SWFObject 2 has something in it for everyone. It offers two distinct methods to embed SWF files, both with a different underlying development philosophy:
Its main advantage is that the mechanism of embedding SWFs relies solely on the object element, so your content can reach a significantly bigger audience than publishing methods that rely on a scripting language. Its biggest disadvantage is that it doesn't offer a workaround for click-to-activate mechanisms in Internet Explorer and Opera imposed by active content. The good news is that Microsoft and Eolas have settled their patent dispute, with the result that active content has already been phased out from most Internet Explorer browsers, so only a very small percentage of visitors will be affected by it.
Dynamic publishing avoids click-to-activate mechanisms by its nature, is less verbose than static publishing and integrates very well with scripted applications. Its biggest disadvantage is that embedding SWFs does also rely on JavaScript, resulting in a smaller coverage than when using static publishing.
SWFObject 2 is an open-source project by Geoff Stearns, the late Michael Williams, and myself. It is the successor of SWFObject 1.5, UFO, and the Adobe Flash Player Detection Kit. SWFObject 2 aims to unify all existing Flash Player embedding methods and provide a new standard for embedding Flash Player content.
You can find the latest version of SWFObject and its documentation on Google Code. Inside the sample download you'll find swfobject_2_1.zip, which contains the following files:
Because having to figure out which markup and JavaScript code to use can be a tedious job, the project provides a publishing tool—as an additional download—called SWFObject Generator to do this work for you. There are two versions available: a simple HTML page and an Adobe AIR 1.0 desktop application. The main difference is that the AIR version can also use copy-to-Clipboard functionality or save your HTML page onto your hard drive. For this tutorial you will use the AIR application.
Note: All downloads are also available in the downloads folder of swfobject_examples.zip.
Extract the swfobject_examples.zip file and open the example_1 folder. It contains the SWFObject 2 JavaScript library, expressInstall.swf, and a test SWF file named test.swf that is 300×120 pixels.
Extract the swfobject_generator_1_1_air.zip file (make sure you have Adobe AIR 1.0 or later installed). Note that the publishing method is static by default. Open SWFObject Generator (see Figure 1) and change the following default parameters:
Click the Save File button, name your HTML file index_static.html, and save it in the example_1 directory. If you open the newly saved index_static.html file in your web browser (make sure you have the latest version of Adobe Flash Player installed), you should see the test SWF file indicating your operating system and Flash Player version (see Figure 2)
Congratulations! You have just embedded your first SWF file using SWFObject 2 static publishing! Easy enough, wasn't it?
Open SWFObject Generator and change the same parameters as before, only now just select Dynamic publishing for the publishing method. Next, click the Save File button, name your HTML file index_dynamic.html, and save it in the example_1 directory. If you open index_dynamic.html file in your web browser, you should again see the test SWF file indicating your operating system and Flash Player version. As you can see, switching publishing modes is as easy as changing a value in one pop-up menu!
When you click the "more" link at the bottom of the SWF definition section of SWFObject Generator, a subsection will expand in which you can fill in all optional attributes and parameters to configure your content.
For more information about what you can do with these parameters, please read the SWFObject documentation or the following Flash Player TechNote: Flash OBJECT and EMBED tag attributes. As an example, disable the default contextual Flash menu by selecting "false" under menu and set the quality of your test SWF file to low by selecting "low" under quality (see Figure 3).
Click the Save File button, name your HTML file index_parameters.html, and save it in the example_1 directory. Open the newly saved index_ parameters.html file in your web browser, and then right-click the SWF to make the minimal context menu visible (see Figure 4).
At the bottom of the SWF definition section, you will find two input fields where you can enter your FlashVars name-value pairs. Just click the add link to add as many new name-value pairs you like. As an example, we have prepared a test SWF file that displays three FlashVars named name1, name2 and name3.
Change the name of your SWF file in the SWF definition section to test_flashvars.swf and add three flashvars named name1, name2 and name3 with a test value of your choice. Next, click the Save File button, name your HTML file index.html, and save it in the example_2 directory. If you open the newly saved index.html file in your web browser, you should see the result shown in Figure 5.
The Alternative content text area in the HTML definition section (see Figure 6) enables you to define fallback content that will be displayed if Flash Player is not installed or supported. When using dynamic publishing, it will also be shown when JavaScript is disabled or unsupported.
Alternative content will also be picked up by search engines, making it a great tool for creating search engine–friendly content. Providing alternative content for SWF files gives an in-depth overview on how you can use alternative content to improve the overall user experience and searchability of your content. By default, SWFObject Generator publishes a "Get Adobe Flash Player" button to point visitors to where they can download the Flash plug-in.
Adobe Express Install is a mechanism built into Flash Player that enables you to download the latest version of the Flash plug-in directly without having to browse to the Adobe website. Express Install is an optional feature for web authors and displays a standardized download dialog box when a visitor has already installed Flash Player 6.0.65 or later on a Windows or Macintosh platform, but a later plug-in version is required. You can activate Express Install by checking the Adobe Express Install checkbox and by adjusting the path to the expressInstall.swf file (which by default assumes it is in the same directory as your HTML file).
When you reuse the dynamic publishing example, just check the Adobe Express Install checkbox. Next, click the Save File button, name your HTML file index_expressinstall.html, and save it in the example_1 directory. If you open the index_expressinstall.html file in your web browser and have an outdated Flash plug-in installed (Flash Player 6.0.65 or later, but lower than Flash Player 9), you should see the dialog box shown in Figure 7.
If you click Yes, Express Install will open a download dialog box with the request to close all browser windows. After installing Flash Player, it will reopen your browser window and redirect you to the page where Express Install was initiated. If you click No, SWFObject will revert to the alternative content. So how can you test all of this? It is our experience that it is best to always first uninstall Flash Player using the Adobe uninstaller, after which you can install an outdated plug-in from the Flash Player archive.
While SWFObject Generator does do a great job in abstracting away the actual writing of the required markup and JavaScript code for you, there are many developers who want to control every aspect of their development work and therefore choose to code or make customizations by hand. If you are interested in what your freshly published HTML page looks like, you can press View source in your browser window or open your HTML file it in a text or code editor.
Open index_static.html from the example_1 directory and have a look at the most important blocks of code. SWFObject static publishing uses the nested-objects method (with proprietary Internet Explorer conditional comments) to ensure the most optimal cross-browser support by means of markup only, while being standards-compliant and supporting alternative content. In the body of your HTML file, you'll find the following block of code:
<object id="myFlashContent" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="300" height="120">
<param name="movie" value="test.swf" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="test.swf" width="300" height="120">
<!--<![endif]-->
<a href="/go/getflashplayer">
<img src="/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
When using the nested-objects method, the following attributes are required:
id (outer object element only; SWFObject needs it for referencing purposes)classid (outer object element only; value is always clsid:D27CDB6E-AE6D-11cf-96B8-444553540000)width (both object elements; defines the width of a SWF file)height (both object elements; defines the height of a SWF file) type (inner object element only; value is always application/x-shockwave-flash)data (inner object element only; defines the URL of a SWF file)The following param element is required:
movie (outer object element only; defines the URL of a SWF file) You can configure your content by using a series of optional attributes and Flash-specific param elements. Because the nested-objects method requires a double object definition, you need to define all optional attributes and nested param elements twice.
In the head of your HTML file, you will find the SWFObject JavaScript library and a line of JavaScript code that registers your SWF file with the SWFObject library and tells SWFObject the Flash Player version for which it is published:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
swfobject.registerObject("myFlashContent","9.0.0");
</script>
swfobject.registerObject accepts the following arguments:
objectIdStr (required) specifies the id attribute to reference the outer object element.swfVersionStr (required) specifies the Flash Player version for which your content is published (format: "major.minor.release" or "major").epressInstallSwfUrlStr (optional) specifies the URL of your express install SWF file and activates Adobe Express Install (a default expressInstall.swf file is included in the SWFObject ZIP archive).For a complete overview on all customization options, please consult the SWFObject documentation.
Open index_ parameters.html from the example_1 directory and have a look at the most important blocks of code. SWFObject 2 works similarly to older versions of SWFObject and UFO, with one main difference: it replaces your entire block of alternative content for the SWF when the required Flash Player and JavaScript support is available, whereas SWFObject 1.x and UFO replace only the content inside the referenced HTML container.
You can basically use any block of HTML code as alternative content as long as your page's markup remains valid when you swap it with the object element; so avoid using elements like tr, td or li as a container, because these will render your page invalid. The actual replacement takes place as soon as the Document Object Model of a web page is ready.
By default, SWFObject Generator publishes the following markup and content:
<div id="myAlternativeContent">
<a href="/go/getflashplayer">
<img src="/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
</div>
In the head of your HTML file, you will find the SWFObject JavaScript library and a few lines of unobtrusive JavaScript to configure and embed your SWF file:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
var params = {};
params.menu = "false";
params.quality = "low";
var attributes = {};
swfobject.embedSWF("test.swf",
"myAlternativeContent", "300", "120",
"9.0.0", false, flashvars, params, attributes);
</script>
The swfobject.embedSWF method has five required and four optional arguments:
swfUrlStr (required) specifies the URL of your SWF file.idStr (required) specifies the id attribute of the HTML element that contains your alternative content to be replaced by your SWF.widthStr (required) specifies the width of your SWF file.heightStr (required) specifies the height of your SWF file.swfVersionStr (required) specifies the Flash Player version for which your content is published (format: "major.minor.release" or "major").epressInstallSwfUrlStr (optional) specifies the URL of your express install SWF file and activates Adobe Express Install. flashvars (optional) is a JavaScript object in which you can specify your FlashVars with name-value pairs.params (optional) is a JavaScript object in which you can specify your nested param elements with name-value pairs.attributes (optional) is a JavaScript object in which you can specify your object element's attributes with name-value pairs.If you don't want to use an optional argument, you can define it as false, 0, or null (or just omit empty trailing arguments). For a complete overview on all customization options or different notation methods on how to write the JavaScript code, please consult the SWFObject documentation. As you can see, dynamic publishing is less verbose than static publishing, and therefore often the easier option when authoring code manually.
SWFObject 2 contains an API that enables JavaScript developers to reuse its internal functions like a box of Lego toys. In total, 11 methods are available. In the static and dynamic publishing sections above, I have already shown you two of them; and in this section, I will discuss five new methods.
The swfobject.getFlashPlayerVersion method returns a JavaScript object that contains the major, minor, and release version numbers of an installed Flash Player.
Note: A version string like WIN 9,0,124,0 as retrieved with ActionScript from within Flash is formatted as OS major,minor,release,build.
The following lines of JavaScript code in the head of your web page will show an alert box indicating your Flash Player version:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var playerVersion = swfobject.getFlashPlayerVersion();
var output = "You have Flash player " +
playerVersion.major + "." + playerVersion.minor + "." +
playerVersion.release + " installed";
alert(output);
</script>
If you browse to the example_3 folder and open index_getflashplayerversion.html in your web browser, you will see an alert like Figure 8.
The swfobject.createSWF method exposes SWFObject's internal cross-browser function to create a SWF file dynamically. This "low level" dynamic publishing method can be very useful when combining it with other JavaScript libraries. It has three required arguments:
attObj is a JavaScript object that contains the name-value pairs of the object element's attributes and values.parObj is a JavaScript object that contains the name-value pairs to define nested param elements.replaceElemIdStr is the id attribute of the HTML element that you want to have replaced by your SWF.Note: You should omit the classid, type, or codebase attributes and movie param element.
The method returns the newly created HTML object element that represents your SWF. Be ware that you should only call this method when the DOM of a web page is available (Tip: use the swfobject.addDomLoadEvent method).
It is wise to always use the swfobject.hasFlashPlayerVersion(versionStr) method in tandem with swfobject.createSWF to ensure that the required minimal Flash Player version is available. The versionStr argument can be formatted as such: "major.minor.release" or "major".
You can use the following lines of JavaScript code in the head of your web page to dynamically embed a SWF file:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
window.onload = function() {
if (swfobject.hasFlashPlayerVersion("9")) {
var att = { data:"test.swf", width:"300", height:"120" };
var par = { menu:"false" };
var id = "myAlternativeContent";
var myFlashContent = swfobject.createSWF(att, par, id);
}
};
</script>
If you browse to the example_3 folder and open index_createswf.html in your web browser, you will see your test SWF file. It will look just like the first instance you saw (Figure 2).
The swfobject.removeSWF method helps to safely remove a loaded SWF file from a web page to avoid broken references and avoid memory leaks in Internet Explorer. Simply pass in the id of the object element with which the SWF file is associated and voila! The following code snippet contains the JavaScript code used in index_removeswf.html from the example_3 folder:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
var params = {};
var attributes = { id:"myFlashContent" };
swfobject.embedSWF("test.swf",
"myAlternativeContent", "300", "120",
"9", false, flashvars, params, attributes);
function addClickHandler() {
document.getElementById("remove").onclick = function() {
if (document.getElementById("myFlashContent")) {
swfobject.removeSWF("myFlashContent");
}
return false;
};
}
window.onload = addClickHandler;
</script>
When you click the link in this example your SWF file will be removed from your web page (see Figure 9).
The swfobject.getQueryParamValue(paramStr) method returns the value of the paramStr parameter in the URL query string or hash string. This method is often used in tandem with FlashVars to pass values from the query string into your SWF, for example:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
if (swfobject.getQueryParamValue("name1")) {
flashvars.name1 = swfobject.getQueryParamValue("name1");
}
var params = {};
var attributes = {};
swfobject.embedSWF("test_flashvars.swf",
"myAlternativeContent", "300", "120",
"9.0.0", false, flashvars, params, attributes);
</script>
If you browse to the example_4 folder and open index_getqueryparamvalue.html in your web browser, you will see the SWF file showing the names of the FlashVars, as shown in Figure 10.
When you append the following string to the query string in the location bar of your web browser:
?name1=getQueryParamValue&name2=is&name3=cool!
And press Return, you will see the SWF file updated to show the values added to the FlashVars.
To secure the method from possible cross-site scripting abuse, SWFObject 2 will encode the returned value—using the JavaScript encodeURIComponent function—if the query string includes one of the following characters: [\"<>.;]
This tutorial should have given you a good overview of how you can use SWFObject 2 to embed SWF files into HTML pages. For further reading, I recommend the following resources:
If you have any questions about SWFObject 2 or have problems with an implementation, please consult the SWFObject 2 FAQ or use the SWFObject 2 Discussion Group.

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License