AS3 getURL solved

February 6th, 2008 by Steven Sacks

One of the things that has become something of a pain in AS3 is getURL. It requires two imports and a try catch. I wrote a little class that simplifies it for me so I can save myself from having to write all that code anytime I want to link to an outside page. Here it is:

Download AS3 GetURL

package net.stevensacks.utils
{
    import flash.net.navigateToURL;
    import flash.net.URLRequest;

    public class Web
    {
        public static function getURL(url:String, window:String = null):void
        {
            var req:URLRequest = new URLRequest(url);
            trace("getURL", url);
            try
            {
                navigateToURL(req, window);
            }
            catch (e:Error)
            {
                trace("Navigate to URL failed", e.message);
            }
        }
    }
}

Usage:

Web.getURL("someurl.html");

Posted in Actionscript, Flash, Tips/Tricks

47 Responses

  1. Johnny

    serious? You need to use this class?

  2. Steven Sacks

    Need? It's called DRY. Why should I ever rewrite all this navigateToURL code? One static method in one place that does it all.

    So, yes, I need to use this class in order to write clean, reusable code.

  3. matt

    nice…I'll be using this. thanks

  4. Quentin

    If you also have an idea on how to avoid new windows being blocked by browsers (Firefox and IE), it'd be awesome!

  5. flashlizi

    to Quentin:
    I give you a way to avoid new window blocked by Firefox/IE.

    code:

    function getURL(url:String,window:String="_blank"):void{ var broswer:String=ExternalInterface.call("function getBrowser(){return navigator.userAgent}") as String; if(broswer.indexOf("Firefox")!=-1 || broswer.indexOf("MSIE 7.0")!=-1){ ExternalInterface.call('window.open("'+url+'","'+window+'")'); }else{ navigateToURL(new URLRequest(url),window); }}

    and the most important is set the wmode property is opaque or transparent.

    for more information,you can see my blog(chinese):
    http://www.riaidea.com/article.asp?id=27

  6. Saturday Night Special

    Nice little class .. Thanks! Gaia looks sweet too.

  7. BrianG

    Sorry, bit of a n00b here. is that javascript for the page as a workaround to the flash getURL calls being popup blocked, or should that be used in the flash file to replace the default getURL function? thanks!

  8. Immo Blaese

    Nice short cut, works really well for me, thanks.

  9. matt

    I think you might be over OOP-ing things… that whole class can be summed up in one line:

    navigateToURL(new URLRequest('blah.com'), '_blank');

    … sure you still have to include navigateToURL and URLRequest, but you'd have to either way… the 'try' function is nice, but it doesn't really add anything to be built in to the class like that… if you could pass in a onFail function, it'd help, I guess…

  10. Ryan

    to: matt

    Good point. Steven is doing things right, but this kind of thing must confuse the hell out of people just starting out. Steven, maybe consider commenting on the one-line solution as well?

  11. Steven Sacks

    First off, you must import flash.net.navigateToURL and flash.net.URLRequest. That's three lines, not one.

    Second, navigateToURL can fail resulting in a runtime error if you don't try…catch it. Many developers aren't familiar with the strict rules of AS3 and continue to code in the loose style of AS1/AS2 without regard for null pointers and runtime errors.

    Third, DRY is not OOP, it's just smart coding, whether you're writing procedural code or object oriented. If you write the same line(s) of code more than once, you should write a subroutine to handle it. It's programming 101.

    And finally, it's a lot less code to import one class and write

    Web.getURL("blah.com", "_blank") ;

    than it is to import two classes and write

    navigateToURL(new URLRequest("blah.com"), "_blank");

    If you don't want to use this class, don't. If you don't see how this class saves coding time and makes getURL easier, oh well. If you think that Matt is right, use his method. It doesn't matter to me.

    :)

  12. Ryan

    Hey man, I'm not trying to say anyone is right. I'd use your class for sure. I guess my point was just that there's a lot of flash users out there that are doing really simple things and aren't really "programmers". Those kind of people are probably still throwing code on a frame in the timeline, and they wouldn't have to import the two classes or go as far as to use yours. So if someone is just making simple banners or something, they probably don't need to worry about really strict code. I guess your blog isn't really for those kind of people though, so I don't know what I'm really saying here.

  13. Steven Sacks

    But, it doesn't matter if the code is on the timeline or not. You have to import those two classes in order to use navigateToURL, that's why getURL isn't so easy anymore, and that's the very reason why importing my one class and not having to pass it a URLRequest yourself (just the url) makes getURL easy again!
    8)

  14. Roberto

    Steven, I need to include this Class in my Flash File. Could it be possible to have an example of how to use it? An .FLA file? Thank you for your assistance.

  15. Steven Sacks

    import net.stevensacks.utils.Web;

    Web.getURL("some.html");

  16. saul

    Great job Mr. Sacks!

  17. Apollo

    Nice job. Simple & elegant. Will come in handy for a project I'm working on. Thanks!

  18. Sean

    Steven, thanks very much for this. This also gave me a better grasp of externalizing functions as classes (if I'm even wording this right). cheers!

  19. Hugh Elliott

    Great little class, Steven. Been using for a couple of weeks in a few projects. Good time-saver. DRY indeed.

  20. john webber

    sweet. this did the trick. first try. AS3 has been quite the learning curve

  21. Casey

    Hey Steven, stumbled upon this while working on a GAIA project coincidentally enough! Anyway, I agree with everything you've done and said except for the static function. I made a similar solution but modeled it after flash.utils.getTimer and the like. It's just an .as file with one public function and no class so you use it like so…

    import com.snaptopixel.utils.getURL;
    getURL("foo.html","_blank");

  22. Blair

    anyone know how to get around myspace blocking a link from flash as3?

  23. Mush Man

    I'm a little inexperienced with Flash, so I don't know how to install classes, like the one you've made. Could you please explain how?

  24. drew

    Maybe I'm missing something… but the way I understand it, navigateToURL just makes an async request for a url. If there's an error, you won't get the error back in the try/catch. You'll get an event a second or so later saying "security exception" or "io exception". You should handle this by adding event listeners to the URLRequest object. The way your code is now, you're not catching either of those errors. Have you ever seen your catch block actually catch anything?

  25. Shanimal

    Drew,

    If allowNetworking is killed in the THML code an exception is thrown immediately.

    And I agree with Steven, if its more than one line of code and I reuse it a million times, it should be in a utility class someplace.

    Steven, you shouldn't let silly people push your buttons.

  26. jackson

    hello and thanks fo this fine tut..
    I am having one problem..
    I can see to manage to compile the web.as into my project..

    Using Adobe CS3.
    My .swf file compiled without error, but the net directory are being leftout.

  27. Lucas

    Hey, I'm a bit of a noob too Steven, so would also be interested in hearing about what BrianG asked a ways back about the code to get around FF and IE detecting the getUrl command as a pop-up:

    code:

    function getURL(url:String,window:String="_blank"):void{ var broswer:String=ExternalInterface.call("function getBrowser(){return navigator.userAgent}") as String; if(broswer.indexOf("Firefox")!=-1 || broswer.indexOf("MSIE 7.0")!=-1){ ExternalInterface.call('window.open("'+url+'","'+window+'")'); }else{ navigateToURL(new URLRequest(url),window); }}

    So this is AS3 and should be entered upon every geturl function I have in my code on my timeline? Or is this java..? I've researched this problem and it amazes me how many different answers there are out there. Haven't tested 'em all (will try more tonight) But it surprises me that there either is a solution or not.. and if there is how come everyone doesn't use the same way, or the simplest one? :)

    I myself am working on a site where I encountered this problem and my friend feels like the visitors are potentially so incompetent that they couldn't click the "allow pop-up"-thing. Which I guess I can see that point.. and would just like to fix it, the easiest/best way :)

    Thank you!

  28. Lucas

    btw, I found that if you use "_parent" instead of "_tab" or "_blank" it will go to the page without warning for pop-ups.. but won't open the page in a new place of course, so I'm still looking to get your code to work!

  29. Lucas

    I aslo stumbled upon this guide, and am seeing many people talk about making a javascript in the actual html page that starts the popup:

    "On your html page within the head tags place this javascript (set the width and height to what you need)-

    function popup(url) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=430,height=550');");
    }

    on your button place the actionscript -

    on(release){
    geturl("Javascript: popup("urltopopup.html");
    } "

    —But even that one doesn't work—

    My browser just tells me this when I click the button:

    TypeError: Error #1006: value is not a function.
    at AA_fla::MainTimeline/pictureClick()

  30. Lucas

    :( Where's our guru..

  31. Steven Sacks

    I am not a Javascript/Browser guru, I'm a Flash guru. ;)

    AFAIK, you cannot circumvent browser popup blockers and that's the end of it. If you call a Javascript method from Flash to open a window you will get blocked. Supposedly, if you use navigateToURL you won't get blocked, but this is guaranteed across all browsers. Safari is a particular jerk about how it blocks stuff.

    You've done your research and you didn't like the answers you found, but I would do the same thing you would do, which is google stuff to figure out my options.

  32. Lucas

    thanks for answering! OKay so, I have this code right now:

    Picture_btn.addEventListener(MouseEvent.CLICK, pictureClick);

    function pictureClick(event:MouseEvent):void
    {
    var request:URLRequest = new URLRequest("http://www.loveinthekgb.com/Picture.html");
    navigateToURL(request, "_tab");
    };

    I'm using navigateToURL, right? Think so. Okay, the strangest thing though, is that this version of the site was started on Adobe cs3:

    http://www.loveinthekgb.com

    and this version was copied off of that project into this version:

    http://www.loveinthekgb.com/realtest

    (^^which has more html code of course aswell.)

    anyways, the second "real test" makes IE and FF block it, and the first it's fine…

    Appreciate the help!!

  33. Jen

    With regards to the pop-up window issue, I had the same problem. All I was trying to do was add a hyperlink, via "getURL", to a button. This line of code worked for me and the browsers didn't block it:

    mybutton.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);

    function mouseDownHandler(event:MouseEvent):void {
    navigateToURL(new URLRequest("http://www.insertWebAddressHere.com/event1/"), "_self");
    }

  34. margot sheehan

    This Web class is really great. I just found it a few days ago. And what makes it even better is that I found it LATE enough that there was already a substantial discussion of related issues…

  35. Tej

    Hi.. Is there a way to force navigateToURL to open html page in specific broswer.. say IE ???

  36. total.lightweight

    This looks *very close* to answering what I've been looking for, and have not been able to find anywhere… How would I take this, and then if the URL fails, load a local swf instead?

    In short, this is for a CD-ROM: Click the button to play a swf that's hosted online (so it will play the most up to date version), but if the user isn't online, they would be presented a generic swf instead that's within the "launch page" swf.

    Thoughts? I've got splinters from banging my head against the wall on this one. Any help would be GREATLY appreciated….

  37. illustrator

    nie little utility class.

    @total.lightweight
    you should put your code in cathc part of the try/catch statement for loading the local swf


    catch (e:Error)
    {
    loadLocalSwf();
    }

    ie: if it fails to navigate to a url online. it will catch an error & you can use error state to call a function to load your local swf

    hope this helps

  38. Michael Bard

    Hi Steven, This looks brilliant. Can you give me a bit more detail about implementing it if I send you one of my getURL scripts that works in every browser except IE?

  39. flash netstream/flv playback problem. - DesignersTalk

    [...] I hope that helps ya… Also, getURL is STUPID in AS3, so you may want to take a look at this: AS3 getURL Solved __________________ audentes fortuna iuvat [...]

  40. slick_vick

    Okay – So I'm trying to use the getURL to open a website in the same window when I press a button and I keep getting compile errors from Flash CS4… The flash fades like it's supposed to, but then it repeats itself.. I've tried everything and cannot get it to work. Someone told me to use this code navigateToURL(new URLRequest("http://www.scattershottheater.com/home.html"), "_self"; and it didn't work after they said it would…. WTF man this has me sooooo pissed off. Can someone give me a hand with this?? I've been researching everywhere and no good news..

    When I used this code navigateToURL(new URLRequest("http://www.scattershottheater.com/home.html"), '_self') I got no compile error from CS4 but now the screen just fades out and it doesnt go to the URL..

  41. slick_vick

    Ok, I'm still having this problem but I figured out that the button is still there after I click it…. The screen fades, but the button is invisibly there, and it seems that the command to get the new url is never executed.. I have over 15 hours straight trying to figure this BS out.. ANy one have an idea or a workaround code that would correct this?? My code is

    stop(); navigateToURL(new URLRequest('http://www.scattershottheater.com/home.html'), '_self')

    and it's on the last frame of the animation.. SOmeone PLEASE help me out here.

  42. kmerlihan

    Hey Steven,
    Thanks for posting this! Works like a charm. I'll be using this everywhere now. See you at FITC.

  43. joey

    thanks steven.

  44. Greg

    Thanks for your somewhat lively debate on this class. By reading your back-and-forth, I have a much clearer picture of the merits of both–and most importantly, feel like I can make those decisions in other contexts without needing to be spoon-fed the answer. Don't flame-war over it. I would have been over my head by it last year but will probably toss this class in place now that my noob shirt is in the laundry. :)

  45. John

    "Need? It's called DRY."

    Yea we get it, but instantiating a new class for a url jump is absurd. I'm not knocking your code Steven it works great. I'm just not sure what Adobe is trying to prove by making this so cumbersome.

  46. artefacto

    Is there a way to make the "hand" cursor action, while passing over the URL link. Like a button?

    Thanks many time

  47. artefacto

    Nevermind, I found it:

    buttonMode = true;
    mouseChildren = true;

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

About Steven Sacks

I am a professional Flash developer with over 13 years of programming experience. I have consulted for high-profile agencies and companies in San Francisco, Los Angeles, Atlanta and New York, and developed numerous award-winning websites and rich internet applications for clients including Adobe, Fox Sports, FX Networks, Anheuser-Busch, GE, DirecTV, ESPN, The Weather Channel, Home Depot, and Coca-Cola.

I am the author of the open-source Gaia Framework for Adobe Flash, which dramatically reduces development time and makes developing Flash sites much easier.