Saturday, June 25, 2011

How to Detect Browser and User Agent in Flash using AS3

Friday, May 20, 2011  Vikrant Agarwal  
In this, 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. Here are the 5 simple steps to create a flash file which can detect Browser and User Agent. Launch the Flash and create a new Flash Document, set the stage size to 400x200px and the frame rate to 24fps.
Create a new ActionScript Class (Cmd+N), save the file as Main.as and start writing below code:
    import flash.external.ExternalInterface;    import flash.events.MouseEvent;    public class Main extends Sprite            more.addEventListener(MouseEvent.MOUSE_UP, showFull);            browserTxt.text = getUserAgent();            letterpress.text = getUserAgent();        private function getUserAgent():String                userAgent = ExternalInterface.call("window.navigator.userAgent.toString");                var browser:String = "[Unknown Browser]";                if (userAgent.indexOf("Safari") != -1)                if (userAgent.indexOf("Firefox") != -1)                if (userAgent.indexOf("Chrome") != -1)                if (userAgent.indexOf("MSIE") != -1)                    browser = "Internet Explorer";                if (userAgent.indexOf("Opera") != -1)                //could not access ExternalInterface in containing page                return "[No ExternalInterface]";        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 of 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. Add the class name to the Class field in the Publish section of the Properties panel.
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.

I hope you liked this tutorial. Thank you for reading!

No comments:

Post a Comment