跨页面通信二(localstorage)

  最近在公司hybird模块开发app中,由于前期native提供的api并不是很完善,很多时间在跨webview无法进行数据交互,大大的降低了用户体验,使得很多操作都无法连贯起来。这里我想到通过onstorage的方式,监听localstorage的变更进行数据交互和回调处理。后来发现onstorage的支持并不是很好,很多时候不能被触发。所以就简单包装了一下localstorage进行一个跨webview的通信。

废话不多说了 直接上代码

 1 ;(function(w){
 2             var ls = w.localStorage;
 3             w.lsSignal = {
 4                 get:function(key){
 5                     return ls.getItem(key);
 6                 },
 7                 set:function(key,val){
 8                     return ls.setItem(key,val);
 9                 },
10                 remove:function(key){
11                     ls.removeItem(key);
12                     return w.lsSignal;
13                 },
14                 claer:function(){
15                     ls.clear();
16                     return w.lsSignal;
17                 },
18                 /*
19                 * @param 回调函数
20                 * 这里使用localstorage进行跨webview通信
21                 * 通过检测localstorage值是否变化进行相关回调操作
22                 * [注意]是websocket和native不支持的前提下采用的一套机制
23                 */
24                 onStorage:function(cb){
25                     var timer = setInterval(function(){
26                             cb(destroy);
27                         },100);
28                     //销毁轮询
29                     function destroy(){
30                         clearInterval(timer);
31                         timer = null;
32                     }
33                     var _onStorage = function(){
34                         //如果onstorage事件可以用则使用原生事件触发,取消轮询
35                         destroy();
36                         cb(function(){
37                             document.removeEventListener("storage",_onStorage,false);
38                         });
39                         
40                     }
41                     document.addEventListener("storage",_onStorage,false);
42                 }
43             }
44         })(window)
45 
46         lsSignal.onStorage(function(destroy){
47             if(lsSignal.get("b") == 1){
48                 console.log("我完成了");
49                 destroy()
50             }
51         })
View Code

 

posted @ 2014-12-24 00:48  river-lee  阅读(482)  评论(0编辑  收藏  举报