panliu888

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用 Flash LocalConnection 解决 IE6/7 postMessage

关于跨域数据交互的总结,请看奇舞团JerryQu的文章 http://www.imququ.com/post/84.html

我们今天聊的主要是 HTML5的新特性 postMessage(跨文档消息传输,使用方式), 这个是个好东西, 网上也有大量的总结。

postMessage 是 IE8, Firefox3, Opera9, Chrome3和 Safari4 支持的。

那么万恶的IE6也想用怎么办?

1、可以通过实时监听 window.name 或 location.hash , http://js8.in/752.html:倒数第二节的描述

2、通过 Flash LocalConnection。

Flash LocalConnection

该对象可在一个 SWF 文件中或多个 SWF 文件间进行通信, 只要在同一客户端就行,跨应用程序, 可以跨域。

利用与JS交互,可以实现JS跨域通信。

 

以下示例代码, 通过 flashobj.SendMessage('msg')  发送消息。

其它页面收到消息后, 会调用 window.ReceiveMessage(msg) 方法,通知消息。 

Flash仅提供字符串传输和通知,如需结构化参数,需在JS里封装。

注意:

  1. 一次发送,最多传输40K的信息。超过40K,可以拆分发送,这个可以在AS里封装一下。
  2. connectionName, 要以下划线(_) 开头, 否则,flash会自动将域加在前面, 导致 connectionName 不同, 无法跨域通信。
 1 package 
2 {
3 import flash.display.Sprite;
4 import flash.events.Event;
5 import flash.external.ExternalInterface;
6 import flash.net.LocalConnection;
7
8 /**
9 * ...
10 * @author panliu888@gmail.com
11 */
12 public class Main extends Sprite
13 {
14 private var con:LocalConnection;
15 private var con_name:String = "_localcon_phx_crossdomain";
16
17 public function Main():void
18 {
19 if (stage) init();
20 else addEventListener(Event.ADDED_TO_STAGE, init);
21 }
22
23 private function init(e:Event = null):void
24 {
25 removeEventListener(Event.ADDED_TO_STAGE, init);
26 // entry point
27
28 initConnection();
29 registerFunction();
30 }
31
32 private function initConnection():void
33 {
34 con = new LocalConnection();
35 con.allowDomain("*");
36 con.client = this;
37 try {
38 con.connect(con_name);
39 } catch (ex:Error) {
40 }
41 }
42
43 private function registerFunction():void
44 {
45 if (ExternalInterface.available)
46 {
47 ExternalInterface.addCallback("SendMessage", sendMessage);
48 }
49 }
50
51 private function sendMessage(msg:String):void
52 {
53 con.send(con_name, "receiveMessage", msg);
54 }
55
56 public function receiveMessage(msg:String):void
57 {
58 if (ExternalInterface.available)
59 {
60 ExternalInterface.call("ReceiveMessage", msg);
61 }
62 }
63 }
64 }



posted on 2012-02-23 17:47  panliu888  阅读(151)  评论(0)    收藏  举报