2009年04月20日
【心得】AS3取得當前位址與網域
在Flash中有時會需要取得自己完整的url或者是domain name,如果是在JavaScript中,用 window.location.href 或者是 window.location.hostname 就可以簡單取得,如:
,由於Flash可以是嵌在網頁或者獨立執行的多媒體,所以取得方式不像JavaScript那麼直覺,主要有幾種作法:
- root.loaderInfo
- LocalConnection
- ExternalInterface
第一種是經由flash本身的loaderInfo資訊:
第三種作法還有更多樣的延伸用法,都是使用JavaScript的函式:
(預設protocol為http, 其它的protocol可能有:https,ftp等)
txt1.text = root.loaderInfo.url;第二種是藉由LocalConnection,但是只能取得Domain:
var conn:LocalConnection = new LocalConnection(); txt2.text = conn.domain;前二者都是取得檔案本身的資訊,也就是說如果A主機的網頁嵌入了放在B主機的flash,則前者都是取得B主機的位址或DN,如果有跨主機,要用第三種方法才能取得所在網頁位址。但由於是透過呼叫JavaScript的語法取得,所以限制較多,必須要置於網頁內才有作用,而且會依瀏覽器版本而有所限制。嵌入語法的allowScriptAccess屬性要設為always。
import flash.external.ExternalInterface;
if (ExternalInterface.available) {
var pageURL:String = ExternalInterface.call('window.location.href.toString');
if (pageURL)
txt3.text = pageURL;
}
得到結果如下: ※ 檔案放在 esabear.googlepages.com
第三種作法還有更多樣的延伸用法,都是使用JavaScript的函式:
var pageHost:String = ExternalInterface.call('window.location.hostname.toString');
var pagePath:String = ExternalInterface.call('window.location.pathname.toString');
var pageProtocol:String = ExternalInterface.call('window.location.protocol.toString');
var userAgent:String = ExternalInterface.call('window.navigator.userAgent.toString');
var platform:String = ExternalInterface.call('window.navigator.platform.toString');
同樣的, 要取得瀏覽器高、寬度, 就置換成'document.documentElement.clientHeight.toString'、'document.documentElement.clientWidth.toString', 或者解析度: 'window.screen.height.toString'、'window.screen.width', 可以舉一反三地運用。
如果需要從url中取得Domain Name,寫了一個小函式:(預設protocol為http, 其它的protocol可能有:https,ftp等)
function url2domain (url:String, protocol="http"):String {
var protocolStr:String = protocol+"://";
var index:int = url.indexOf (protocolStr);
return (index == -1) ? null : url.substring (protocolStr.length, url.indexOf ("/", protocolStr.length));
}
trace (url2domain ("http://www.google.com.tw/somePath/example.swf", "http"));
相關閱讀:
※ 註:用 fscommand 其實也可以實作,只是不方便也不實用。引用URL
http://cgi.blog.roodo.com/trackback/8761867
回應文章 

你好,我想請問是否有http://esabear.googlepages.com/self_location.swf的source檔.fla呢?因為我在IE中嘗試,幾乎都失敗。可以幫我一下嗎?感激
Posted by Walter
at 2009年07月21日 16:19
http://esabear.googlepages.com/self_location.fla
程式碼有打錯嗎 也許是篏入Flash的語法有問題吧
allowScriptAccess要設為true喔
網頁篏Flash的方式五花八門 各種語法會有出入 要注意一下
Posted by 熊
at 2009年07月21日 16:59