Read More Ninja Action!

Adding web links to Flash in Actionscript 3 using NavigateToURL

Hello everyone, welcome to another NinjaCamp tutorial here at experts.ninjacamp.com! This time around I'll be showing you how to navigate to web links from within your Flash movies.

In actionscript 2, we could use the getURL method to do this. It was pretty simple, but things have changed a bit in Actionscript 3. Let's look at a finished block of code with this functionality and then take it apart line-by-line:

myBtn.addEventListener(MouseEvent.CLICK, gotoUrl);

function gotoUrl(ev:MouseEvent):void
{
var url:String = "http://www.ninjacamp.com";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}

Pretty easy! Let's take a look. In line 1 we are adding an event listener for our button. This is the same easy stuff I covered in another tutorial here, and just makes it so that when you click the button a function is called- in this case it's our gotoUrl function.

Now we define our function in the next block of code. In line 4 we need to define our target web address. We create a new String variable (since it's just a string of text) and put the full address with http:// in quotes. Simple.

Next, in line 5, we define our URLRequest object. This is where the AS3 version of this process gets a little wordy! In basic terms we are wrapping our URL text into a format Flash can accept with its navigateToURL method.

The next part is optional but usually good practice. We wrap the actual navigation code in a try catch statement. This is a way for Flash to catch errors as they happen and handle them without borking the whole movie. Basically, we use this because if the URL is dead we want to be able to continue the movie gracefully. Just put any code you want to execute if it errors out in the "catch" section of the statement.

Line 7 is where we actually execute the code to go to the web address specified in line 4. It works very similarly to getURL, we just hand it our "request" variable, and tell it to launch in a "_blank" window. You could replace blank here with "_self", "_parent", or any other named window you're manipulating with javascript or the like. It's just a string and works like regular href tags in HTML. That's about it! I've included a sample FLA below so you can see everything working together. Thanks and have fun!

Sample (AS3, Flash CS4)