高見龍

iOS app/Ruby/Rails Developer & Instructor, 喜愛非主流的新玩具 :)

Data Loading From Other Domain

最近用Flash做了一個可以在網路廣告素材上面直接投票的東西,但卻發現原來放在廣告網站的swf檔,沒法子直接跨網域的存取資料,翻了一下網路上的資料才發現原來這是為了安全性的考量所設計的,沒法子直接存取,所以例如XML.load(), XML.sendAndLoad(), LoadVars.load(), LoadVars.sendAndLoad(), loadVariables(), loadVariablesNum()等等,都會有這方面的問題。

解決辦法:

在網站根目錄下面放一個定義cross-domain policy的XML檔案(檔名為crossdomain.xml)就行了。檔案內容如下:

<?xml version=”1.0″?>
<cross-domain-policy>
    <allow-access-from domain=”www.eddie.com.tw” />
    <allow-access-from domain=”*.yahoo.com” />
    <allow-access-from domain=”105.216.0.40″ />
</cross-domain-policy>

可以定義完整的Domain名稱,或是某個網域,甚至是指定某個IP也可以。如果不想一個一個設定,或是來源可能有很多個地方,也可以用下面這種做法:

<cross-domain-policy>
    <allow-access-from domain=”*” />
</cross-domain-policy>

其實每個裡面有個optional的屬性secure,底下是它的說明:

Each tag also has the optional secure attribute. The secure attribute defaults to true. You can set the attribute to false if your policy file is on an HTTPS server, and you want to allow SWF files on an HTTP server to load data from the HTTPS server.

Setting the secure attribute to false could compromise the security offered by HTTPS.

If the SWF file you are downloading comes from a HTTPS server, but the SWF file loading it is on an HTTP server, you need to add the secure=”false” attribute to the tag, as shown in the following code:

A policy file that contains no tags has the same effect as not having a policy on a server.

在Flash Player 7 r19之後的版本支援以下指令:

System.security.loadPolicyFile(http://www.eddie.com.tw/abc/123.xml);

如此一來,這個XML檔案就不一定要放在根目錄底下,而且也不一定只能用crossdomain.xml來命名。

參考資料:

  1. Macromedia LiveDOC
  2. Flash ActionScript RIA應用程式開發(Luar著)

Comments