如何使用Flash(AS3)从远程域调用Flex SWF?
时间:2020-03-05 18:40:17 来源:igfitidea点击:
我有一个托管在http://www.a.com/a.swf的Flex SWF文件。
我在另一个尝试加载SWF的doamin上有一个Flash代码:
_loader = new Loader(); var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf"); _loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish); _loader.load(req);
在onLoaderFinish事件上,我尝试从远程SWF加载类并创建它们:
_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class
运行此代码时,出现以下异常
SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf. at flash.display::LoaderInfo/get applicationDomain() at NuconomyLoader/onLoaderFinish()
有什么办法可以使此代码正常工作?
解决方案
回答
也许是我们需要System.Security.allowDomain?
回答
第550页的Adobe Flex 3编程ActionScript 3 PDF(第27章:Flash Player安全性/交叉脚本)中对此进行了全部描述:
If two SWF files written with ActionScript 3.0 are served from different domains—for example, http://siteA.com/swfA.swf and http://siteB.com/swfB.swf—then, by default, Flash Player does not allow swfA.swf to script swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains by calling Security.allowDomain(). By calling Security.allowDomain("siteA.com"), swfB.swf gives SWF files from siteA.com permission to script it.
它用图表和所有内容进行了更详细的介绍。
回答
在服务器上需要一个crossdomain.xml策略文件,该文件具有要加载的文件,它看起来应该像这样:
<?xml version="1.0"?> <!-- http://www.foo.com/crossdomain.xml --> <cross-domain-policy> <allow-access-from domain="www.friendOfFoo.com" /> <allow-access-from domain="*.foo.com" /> <allow-access-from domain="105.216.0.40" /> </cross-domain-policy>
将其作为crossdomain.xml放入要从中加载的域的根目录中。
另外,我们需要设置加载程序以如下方式读取该文件:
var loaderContext:LoaderContext = new LoaderContext(); loaderContext.checkPolicyFile = true; var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete ); loader.load( new URLRequest( "http://my.domain.com/image.png" ), loaderContext );
从http://blog.log2e.com/2008/08/15/when-a-cross-domain-policy-file-is-not-enough/获得的代码示例