Get current url to Flash swf using an External Interface call

Update: please see the newer tut talking about getting the current url with as3

Overview:

Many have struggled with the task of getting you swf to read or get the current url showing in the browser, the html page the browser is at which has the swf embedded. Not to be confused with the _root._url which returns the path of the swf file. This would be helpful to know if someone is embedding your swfs on their site, or even customize your swf depending on which page it resides on. There is a pretty simple, yet virtually undocumented way to do this. We have to use javascript by calling External Interface and get the url from the DOM. Window.location.href. Then we must call the toString() function only because ExternalInterface.call requires a function rather than only reading a static property.

Steps:

  1. Import external interface into your file: import flash.external.ExternalInterface;

  2. Initialize a variable to store the url path: var urlPath;

  3. Create a function to call external interface and assign the html page path to your variable: urlPath = ExternalInterface.call(“window.location.href.toString”);

  4. Call the function when/if needed.

Example:

With javascript: window.location.href or window.location.href.toString();
With actionscript: ExternalInterface.call(“window.location.href.toString”);
External Interface html Example

Get Adobe Flash player


Actionscript:

import flash.external.*;
var urlPath;

function geturlhttp() {
urlPath = ExternalInterface.call("window.location.href.toString");
}
geturlhttp();
//Here I assign the url to a text box on the stage
_root.urlText.text = urlPath;

Download:

ExternalInterface.zip

This entry was posted in tutorial and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

37 Comments

  1. Jason
    Posted January 17, 2008 at 5:27 pm | Permalink

    Great but you can\’t get URLs from Myspace/Facebook because of Javascript is not allowed. Please vote to fix the bug below so we have this information everywhere.

    The browser URL information is actually available in the Error Code returned from a call to ExternalInterface (when Javascript is not allowed). This information is not available in the standard player (but is in the debug), ARGH…. We all want to track our Flash widgets so please vote to fix this bug. You would then be able to get the browser URL from the Error code returned on the API call from Myspace page (a bit of a hack but the information would be available).

    http://bugs.adobe.com/jira/browse/ASC-3095

  2. DB
    Posted January 24, 2008 at 8:30 pm | Permalink

    this doesn’t work in IE… alot of people having trouble with this :/

  3. Posted January 25, 2008 at 11:12 am | Permalink

    It is interesting, it seems to have a lot to do with the Microsoft’s dealings with Active content. Clicking on the “External Interface html Example” link does work in IE. I have struggled at getting this to work in IE scenarios also. Any suggestions?

  4. Posted January 27, 2008 at 3:24 am | Permalink

    You can also use location.href and pass it through SWFObject to get the current url of a page like:

    so.addVariable(“urlPageName”, location.href);

    I used it a couple of times across projects that needed to work locally and on the server. This worked fine for me across IE and Firefox.

  5. Posted February 1, 2008 at 11:54 am | Permalink

    @Evan – Thanks for this, learnt something new – just a shame it doesn’t play ball in IE.

    @agi – Good suggestion, I think that’ll work…

  6. Ed McManus
    Posted February 8, 2008 at 10:41 pm | Permalink

    Hi Guys,

    Just thought you might like to know there’s a solution to this problem. The following snippit works across all browsers I’ve tested (tho clearly it requires JS access):

    var result:String = ExternalInterface.call(‘eval’, ‘window.location.href’);

    Hope it helps!

  7. Posted March 4, 2008 at 10:16 am | Permalink

    I developed a new simple web tool that uses FScommand from flash and SWFObjecy implementation from the Javascript side. The two pair up nicely to make a functional addressing system in flash.

    Check it out => http://flashURL.net

  8. Posted March 20, 2008 at 11:30 pm | Permalink

    I’ve written an updated post on this subject see Get Current URL and Query String Parameters

  9. John T. Bailey
    Posted May 20, 2008 at 10:36 am | Permalink

    What is the advantage of using the ExternalInterface technique as you’ve described over the following:

    [actionscript]
    import flash.net.LocalConnection;
    var lc:LocalConnection = new LocalConnection();
    var domain:String = lc.domain;
    trace(domain);
    [/actionscript]

    • oxygen
      Posted August 30, 2011 at 11:30 am | Permalink

      @John

      or shorter:

      import flash.net.LocalConnection;
      trace(new LocalConnection().domain)

  10. Sander van den Berg
    Posted May 29, 2008 at 9:55 am | Permalink

    Hello all!

    @John: Think this will only give the URL of the location of the SWF, it won’t give you the URL of the screen in which you are viewing the SWF.

    for example:
    domain 1: contains SWF
    domain 2: contains html file with embed sourcecode.

    You want the URL of domain 2, so you can track ur SWF.

    This is my issue aswell. Since im gonna work with paying clients, having their own layout. I want to dynamicly get their XML file containing layout info (which is on my server) based on a URL or Domainname send by them automaticly when viewing my SWF.

  11. nick
    Posted May 29, 2008 at 9:29 pm | Permalink

    I’m trying to use this function to insert the current url when people submit a form, the code is below but the import flash.external.*; is created an endless loop how can I fix it, and is the way im getting the url ok or should i just put it into a variable instead of using the function? I appreciate any help

    thanks

    stop();
    System.useCodepage = true;
    send_btn.onRelease = function() {

    import flash.external.*;

    function geturlhttp() {
    _root.urlPath = ExternalInterface.call(“window.location.href.toString”);
    }

    my_vars = new LoadVars();
    my_vars.url = geturlhttp();
    my_vars.email = email_box.text;
    my_vars.name = name_box.text;
    if (my_vars.name != “” and my_vars.email != “” and my_vars.url != “”) {

    my_vars.sendAndLoad(“mailer.php”, my_vars, “POST”);
    gotoAndStop(2);
    } else {
    error_clip.gotoAndPlay(2);
    }
    my_vars.onLoad = function() {
    gotoAndStop(3);
    };
    };
    email_box.onSetFocus = subject_box.onSetFocus=message_box.onSetFocus=function () {
    if (error_clip._currentframe != 1) {
    error_clip.gotoAndPlay(6);
    }
    };

  12. Posted November 18, 2008 at 2:48 am | Permalink

    Hi,all
    ExternalInterface.call(’eval’, ‘window.location.href’);
    this can get url,but i have a problem,my flash is a widget and when it insert into a page,this widget has not a id(<object classid=…. id=…) and not work.
    how can i do ?

  13. Posted November 18, 2008 at 8:29 am | Permalink

    @Kavin – your flash does not need an id or class to use ExternalInterface. Although sites lie MySpace don’t allow the use of javascript, so we can’t use ExternalInterface there. Good luck!

  14. kallal
    Posted November 26, 2008 at 6:02 pm | Permalink

    This used to work fine in older versions during the AS1 days. What broke?

  15. Adrian
    Posted April 24, 2009 at 3:34 am | Permalink

    I tried to use your code below but it is not working in my end.

    The return value is “undefined”.

    I am currently experimenting on how can I get the querystring of the current URL and append it in the url in of my getURL function.

    Below is a sample of my code.

    *********************************************
    import flash.external.*;

    function geturlhttp()
    {
    //will contain the Current URL
    var urlPath = ExternalInterface.call(“window.location.href.tostring”);

    //trace (urlpath)
    // result is undefined
    //get current URL of the site
    var QStr:String;
    Qstr = “”;
    if (urlPath.indexOf(“?”) -1)
    {
    Qstr = urlPath.substr(urlPath.indexOf(“?”), urlPath.length );
    }

    getURL(“http://www.adrian.com/adrian.html” + Qstr , “_self”);

    }

    _root.LearnD.onRealease = function()

    {
    geturlhttp();
    };

    *********************************************
    Whenever I click the LearnD button , I am redirected to this page.

    http://www.adrian.com/adrian.htmlundefined

  16. Posted April 24, 2009 at 9:46 am | Permalink

    @Adrian – this line is most likely giving you trouble:
    if (urlPath.indexOf(”?”) -1)
    should it read:
    if (urlPath.indexOf(”?”) == -1) ?
    let me know if that does it. happy scripting.

  17. Adrian
    Posted April 26, 2009 at 12:34 am | Permalink

    I correct the codes aand the issue is still existing.

    I am still getting “undefined”. I also noticed that the code is working if I will assign a fixed URL value for the UrlPath variable.

  18. Posted April 27, 2009 at 11:56 am | Permalink

    Actually, it should be != rather than ==, and remember that variable names are caSe seNseTive, so your QStr and Qstr are not the same things.

    this worked for me:

    function geturlhttp() {
      //var urlPath = ExternalInterface.call("window.location.href.tostring");
      urlPath = "http://www.adrian.com/adrian.html?test=qs";
      //trace (urlpath)

      var QStr:String = "";
      if (urlPath.indexOf("?") != -1) {
        QStr = urlPath.substr(urlPath.indexOf("?"), urlPath.length );
        trace(QStr);
      }

      getURL("http://www.adrian.com/adrian.html" + QStr , "_self");

    }
  19. Keith
    Posted May 13, 2009 at 11:57 am | Permalink

    This page claims to provide the URL to the SWF but it does not. The example provided, and all of the alternative examples in the comments, provide the URL to the PAGE containing the SWF.

  20. Posted June 8, 2009 at 9:05 am | Permalink

    Thanks for the solution, that’s what I was looking for.

  21. Posted June 22, 2009 at 2:39 am | Permalink

    Hi,

    I don't really like to require users of my swf's to have to add and javascript, so instead I do this entirely in actionscript:

    ExternalInterface.call(“eval”,”document.location.href”);

    You have to use “eval” (evaluate) to work across all browsers (and “document.location” is safer than “window.location” in case you're in a frameset).

    HTH,

    MicroAngelo

  22. Posted February 25, 2010 at 5:43 am | Permalink

    You are perfect!

    I am too many time finding it, very nice and wonderful working.

    Thanks again!

  23. Hieu
    Posted March 4, 2010 at 4:41 am | Permalink

    Thanks a lot for sharing.

  24. Posted March 24, 2010 at 1:14 pm | Permalink

    thaaaaaaaaaaaaaaaaaaaaaaaaaaaaanks for all so much

    you’ve helped me so so so much

    I’m working on my project and I’ll show after finish what I did !!!!!!!

    thanks again

  25. Posted March 26, 2010 at 9:40 am | Permalink

    hello guys

    how can I check urlpath what starts with ??

    i.e :

    I have a link for example : http://circlecube.com/

    and after getting urlpath by :

    var urlPath = ExternalInterface.call(“window.location.href.tostring”);

    check if it starts with : http://circlecube.com/

    if true trace(yes) or trace(not)

    I tried to make this condition but I couldn’t

    can any body help me please ????

  26. Posted April 6, 2010 at 9:54 am | Permalink

    Sorry, for stupid question ……..How do I Get URL into Flash

  27. Posted May 29, 2010 at 2:21 am | Permalink

    similar problem of endless loop. need to look into the issue

  28. jason
    Posted July 27, 2010 at 2:47 pm | Permalink

    how did you get the example to work in this page? How did you call the .js? Did you embed it in the template file or how in the page?

  29. Posted July 27, 2010 at 3:45 pm | Permalink

    Hi guys,
    I use this:

    var current_domain;
    function geturlhttp()
    {
    current_domain = ExternalInterface.call(“window.location.href.toString”);
    }
    geturlhttp();
    trace(current_domanin);

    and in embed code: allowscriptaccess=”always”
    and works fine.

  30. Posted August 2, 2010 at 11:59 am | Permalink

    Excelente!!! muchas gracias

  31. Posted October 16, 2010 at 11:01 am | Permalink

    Thanks, Great post!

  32. Posted January 2, 2011 at 4:45 pm | Permalink

    thank for this post!

  33. Posted February 5, 2011 at 7:38 pm | Permalink

    Thankyou for helping out, wonderful information.

  34. Posted August 7, 2011 at 3:44 pm | Permalink

    thanks. Especially for source documents :)

  35. Posted September 1, 2011 at 6:50 pm | Permalink

    Worked! Thanks!

3 Trackbacks

  1. [...] browsers and without having to rely on flashvars or javascript, but to just have it work. I wrote a post on it earlier, although it seemed it wouldn’t play nice with Internet Explorer IE, I later [...]

  2. [...] browser. I’ve written about the following methods before, but they were in as2 with “Get current url to Flash swf using an External Interface call” and “Get Current URL and Query String Parameters to Flash in as2“. In as3, [...]

  3. [...] Get current url to Flash swf using an External Interface call | circlecube [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    Developing for old browsers is (almost) a thing of the past – (37signals)

    Basecamp announces that it’s new version will not support old browsers! They will of course continue to support them in their “classic” version. But this is good news and as more implement this type of policy the internet will be happy. It used to be one of the biggest pains of web development. Juggling different [...]

    Screen shot 2012-02-10 at 12.59.33 PM

    Vendor Prefixes – about to go south

    What are “standards” coming to? Who’s guilty? Apple and Chrome: They’re supporting vendor prefixed properties like they’re a standard part of development. Firefox, Opera and Internet Explorer: They should have been on the ball more. Need to push their evangelism further. Teach developers that it’s not exclusively -webkit to style elements. All the browsers: experimental [...]

    bio

    An Event Apart Notes: Ethan Marcotte, Responsive Web Design

    Ethan Marcotte has become the father of Responsive Web Design and spent this whole day focused on principles, techniques, gotchas, examples, … all about building and how to build responsive sites. With a sprinkle of mobile first. For Ethan, it all started with this article: http://www.alistapart.com/articles/dao/ Think of architecture, the whole design phase is established [...]

    Webcomm_Montreal

    An Event Apart Notes: Jared Spool, The Curious Properties of Intuitive Web Pages

    Senseless waste of asterisks… Avis used an asterisk to denote optional fields. This means that there is a lot of baggage that comes with an asterixk. Somewhere this symbol got meaning, it’s not in the bible! We can control when something goes from unintuitive to intuitive. A design is intuitive (although technically and grammatically speaking [...]

    untitled-158-2

    An Event Apart Notes: Marco Arment, Bridging the App Gap

    The iPhone changed our industry in 2007: first mobile to have a desktop class web browser and it made people start using their mobile phones as computers! All apps other than apple provided ones were web browser apps. Most of the first apps were branded web browsers. No real difference between using mobile site or [...]

    lukew_space

    An Event Apart Notes: Luke Wroblewski, Mobile to the Future

    MASS MEDIA (in waves) Print, Recordings, Cinema, Radio, Television, Internet, Mobile Mobile is the new Mass Media It certainly is mass and massive. More mobile devices (by far) every day than babies born on the planet. Mobile devices are eating into our personal computing shares. New waves of mobile media eat all previous media waves. [...]

    IMG_4500

    An Event Apart Notes: Josh Clark, Buttons are a Hack

    Mobile and touch should be revolutionizing design and user experience. We don’t want to touch a tiny link or button. Back button is just stupid. Fitz’s Law, make things fat proximal targets for easy touching. People are lazy, let’s as designers LET people be lazy! Maybe even use the whole screen as your control. Eliminate [...]

    nicole_pink_bkg_2012

    An Event Apart Notes: Nicole Sullivan, Our Best Practices are Killing Us

    Grep to for analyze css. CSS duplication is a web-wide problem. Started helping facebook optimize thier site and they had 1.9MB of css loading. The same color showing up hundreds of times. Many many color statements and declarations. !important declarations get dangerous. Sites found to have over 500 !important declarations! float is a serious problem [...]

    ericmeyer

    An Event Apart Notes: Eric Meyer, The Future of CSS

    Cormorant trained to fish for the fishermen. The fishermen tie bands around the birds necks that are. Fishermen fish at night, using lamps they attract bugs, which attract fish, and the cormorant get to fish but cant swallow them and the fishermen take the fish. Browser vendors are promising us new CSS tools, but don’t [...]

    sammyj

    An Event Apart Notes: Ethan Marcotte, Rolling Up Our Responsive Sleeves

    Henry Adams (Descendant of 2 presidents: great-grandson to John Adams and grandson to John Quincy Adams). He lived between the civil war and world war 1. He witnessed the industrial revolution. Chaos was the law of nature, Order was the dream of man Samuel Johnson – funniest man in the 17th Century… Responsive Design: 1. [...]

  • Recent Comments

    me-gamer

    me-gamer

    this is really nice. this made many of my task simple.
    Lori Newman

    Lori Newman

    Just wanted to thank you for your presentation. It was extremely informative and just what I...
    Karl

    Karl

    I have been using for some time this nice Banner, from developer FX. They have a really nice Live...
    Karl

    Karl

    Thank you for this wonderful link… recommend it! Fast, simple, easy… :-)
    Gabriel

    Gabriel

    Hi Valerie, I don’t know if you are still following this post, but I tried seeing if it is...
    avinash

    avinash

    Hi Evan, I am using the same code and trying it on chrome/firefox it is not working on neither...