Advertisement
ActionScript

Quick Tip: Detect the Browser and User Agent with AS3

by

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 Main.as and start writing:

package 
{
	import flash.display.Sprite;
	import flash.external.ExternalInterface;
	import flash.events.MouseEvent;
	import fl.transitions.Tween;

	public class Main extends Sprite
	{
		private var userAgent:String;

		public function Main():void
		{
			more.addEventListener(MouseEvent.MOUSE_UP, showFull);
			browserTxt.text = getUserAgent();
			letterpress.text = getUserAgent();
		}

		private function getUserAgent():String
		{
			try
			{
				userAgent = ExternalInterface.call("window.navigator.userAgent.toString");
				var browser:String = "[Unknown Browser]";
	
				if (userAgent.indexOf("Safari") != -1)
				{
					browser = "Safari";
				}
				if (userAgent.indexOf("Firefox") != -1)
				{
					browser = "Firefox";
				}
				if (userAgent.indexOf("Chrome") != -1)
				{
					browser = "Chrome";
				}
				if (userAgent.indexOf("MSIE") != -1)
				{
					browser = "Internet Explorer";
				}
				if (userAgent.indexOf("Opera") != -1)
				{
					browser = "Opera";
				}
			}
			catch (e:Error)
			{
				//could not access ExternalInterface in containing page
				return "[No ExternalInterface]";
			}

			return browser;
		}

		private function showFull(e:MouseEvent):void
		{
			info.fullInfo.text = userAgent;
			var tween:Tween = new Tween(info,"y",null,info.y,180,0.5,true);
		}
	}
}

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

Conclusion

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!

Related Posts
  • Code
    Android SDK
    Create a Music Player on Android: Project Setup0d63m preview image@2x
    The Android platform provides resources for handling media playback, which your apps can use to create an interface between the user and their music files. In this tutorial series, we will create a basic music player application for Android. The app will present a list of songs on the user device, so that the user can select songs to play. The app will also present controls for interacting with playback and will continue playing when the user moves away from the app, with a notification displayed while playback elapses.Read More…
  • Code
    HTML5
    HTML5: Vibration APIPdl54 preview image@2x
    HTML5 has been a breath of fresh air for the web, which hasn't only affected the web as we know it. HTML5 provides a number of APIs that enable developers to create interactive websites and improve the user experience on mobile devices. In this article, we'll take a closer look at the Vibration API.Read More…
  • Game Development
    Implementation
    Write Once, Publish Everywhere With HaxePunk: Making a GamePreviewretinaimage
    You've probably had this experience before: you hear about an awesome game, but then you find out that it's only coming out on the one platform that you don't own. It doesn't have to be this way. In this tutorial, you will learn how to use Haxe to make a game in one development platform that can target multiple gaming platforms, including Linux, Mac, Windows, iOS, Android, and Flash.Read More…
  • Code
    JavaScript & AJAX
    JavaScript Animation that Works (Part 4 of 4)Spriting icon large
    In the first part of this series, we introduced the idea of using spriting as an easy, cross-browser way of having interactive animation for the web. In the second part, we got some animation working, and in the third we cleaned up our code and made it ready for the web. Read More…
  • Code
    JavaScript & AJAX
    Creating Brackets ExtensionsDeeper in brackets retina preview
    A little while ago I wrote about the recent updates to the Brackets editor. Brackets is an open source project focused on web standards and built with web technologies. It has a narrow focus and therefore may not have a particular feature you've come to depend upon. Luckily, Brackets ships with a powerful extension API that lets you add any number of new features. In this article, I'm going to discuss this API and demonstrate how you can build your own extensions.Read More…
  • Code
    Other
    Client-Side Security Best PracticesSecurity best practices retina preview
    Thanks to HTML5, more and more of an applications' logic is transferred from server-side to client-side. This requires front-end developers to focus more on security. In this article I will show you how to make your apps more secure. I will focus on techniques that you may not have heard about, instead of just telling you that you have to escape HTML data entered in by users.Read More…