Students get a Tuts+ subscription for just $45! Hurry limited offer.

Quick Tip: Detect the Browser and User Agent with AS3


Follow this Quick Tip to learn how to detect the Internet Browser and User Agent using AS3 and Flash.

Step 1: Brief Overview

We'll use TextFields and the help of ExternalInterface to retrieve the User Agent, through a JavaScript call, and display it in our SWF. With the User Agent stored, a simple search through the returned String will give us the Internet Browser.

Step 2: Set up Your Flash File

Launch Flash and create a new Flash Document, set the stage size to 400x200px and the frame rate to 24fps.

detect browser and user agent flash

Step 3: Interface

detect browser and user agent flash

This is the interface we'll be using, refer to the image above for the instance names. Recreate it yourself or simply use the Source FLA.

Step 4: ActionScript

Create a new ActionScript Class (Cmd+N), save the file as and start writing:

An ExternalInterface call to a JavaScript function will get the User Agent string and use the indexOf() method to search for each browser's ID within that string; if the User Agent string contains the name of the browser you are looking for, you can assume that is the browser which the user is using. You can add a specific browser in this area. The more button will animate the info panel to the stage and reveal the full User Agent Information.

If the ExternalInterface call fails, the try-catch statement will pick this up and return a simple error message to the text box. It may fail if the SWF is being run in standalone Flash Player, or if the containing webpage prohibits its use.

Step 5: Document Class

Remember to add the class name to the Class field in the Publish section of the Properties panel.

detect browser and user agent flash

Step 6: Publish

In order to see the SWF in action (it can give you errors when testing in the IDE) you must open the file in the browser, you can press Shift+Cmd+F12 (File | Publish) to Publish a HTML file and then open it, or drag the SWF from your project folder to the browser to see the file working.

detect browser and user agent flash


You can make specific changes to your application based on the browser and User Agent data obtained.

Be careful with this; using the user agent string is considered unreliable, as users can alter the contents of this string in various ways. Some browsers even have a feature that allows them to masquerade as other browsers by changing their own user agent string. It would be unwise to lock the user out of a site (or to only let them in to a site) based only on the user agent string.

I hope you liked this Quick Tip, thank you for reading!