Tuesday, December 2, 2008

Accessing HTML page details

Flash only has a basic in-built property to retrieve details of the HTML page in which an SWF is embedded. You can retrieve the URL of the SWF file itself, for example with the following code:

myTxt.text = this._url;

Later versions of the Flash player also allow you to retrieve the URL of any JPEGs, GIFs or PNG files by applying the _url property to a movieclip into which any of those filetypes has been loaded.

However, to retrieve the page URL, you have to use External Interface to communicate with the page directly. For example, the following code will retrieve the page URL:

import flash.external.ExternalInterface;
var pageURL = ExternalInterface.call('window.location.href.toString');
myTxt.text = pageURL;

A similar technique can be used to retrieve the HTML page title:

import flash.external.ExternalInterface;
var pageTitle = ExternalInterface.call('window.document.title.toString');
myTxt.text = pageTitle;

With both techniques, you can also consider using Flash's unescape function to convert any URL-encoded characters into ASCII strings:

myTxt.text = unescape(myTxt.text);

Finally, it's possible to use ExternalInterface to change details of the HTML page rather than just retrieving them. Create an FLA containing a dynamic text field and a button. Add the following code:

import flash.external.*; // imports the external interface class
var newTitle:String;
btn.onPress = function() {
newTitle = String(ExternalInterface.call("changeDocumentTitle", title_txt.text));
};

Publish the SWF file and the corresponding HTML page. Now edit the HTML page and add the following javascript code:

<SCRIPT LANGUAGE="JavaScript">
function changeDocumentTitle(a) {
if (a != null) {
window.document.title=a;
window.document.write;
}
}
</SCRIPT>

If you upload the SWF and HTML page, you should now be able to change the HTML page title dynamically from Flash. You can see a working example here and get the source files here.

Obviously you wouldn't necessarily want to use a text field to do this but, by storing newTitle as a variable, you can alter the HTML page dynamically, for example as part of a Flash navigation.