美文网首页
JavaScript跨域共享本地localStorage数据

JavaScript跨域共享本地localStorage数据

作者: 独孤流 | 来源:发表于2019-08-29 16:54 被阅读0次

    参考资料:

    Tips:

    经测试:iOS的 UIWebViewWKWebViewSFSafariViewControllerSafari几个只能在组件内部共享数据,
    UIWebView是同一个应用共享数据
    WKWebView初始化时会共享数据,但在同时出现的多个之间不会共享,也就是说在初始化时复制一份,销毁时在保存到共享数据里去,同一个应用同时存在的不同的对象之间也不共享数据,如果一次性只出现一个对象,则和SFSafariViewController一样
    SFSafariViewController,因为一次只能打开一个,所以同一个应用不同对象共享数据

    Tips2:

    iPhone的Safari无痕浏览模式下点击右下角新开一个窗口打开一个页面会丢失存在浏览器里的小心

    tmp7cbb7cfc.png

    前言

    在做iOS超级签名时想优化一下体验,就是一台设备如果用户已经读取过设备信息,则以后其他网站都不再读取,毕竟再次读取信息麻烦也比较耗时,也就是不同的站点都要共享一个十分已经阅读过该设备的信息,于是请教周围同事并百度谷歌一番后找到了这种跨域共享数据的方式

    现有A网站、B网站、C网站都要共享一个localstorage的信息,使用X网站的temp.html临时保存交互,写法如下
    A网站的a.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="edge">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="renderer" content="webkit">
        <meta name="renderer" content="ie-comp">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Cache-Control" content="no-cache">
        <meta http-equiv="Expires" content="0">
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
        <meta name="format-detection" content="telephone=no">
        <meta name="format-detection" content="email=no">
      </head>
      <body>
        <a href="javascript:readItem();">read</a>
        <a href="javascript:saveItem();">save</a>
        <a href="javascript:deleteItem();">delete</a>
        <h>我是A</h>
        <textarea name="name" rows="8" cols="80" id="txt1"></textarea>
        <iframe id="ifr_localStorage" src="http://xxxx/temp.html" style="display:none;" ></iframe>
          <script type="text/javascript">
    
              /**
              * 监听跨域传来的数据
              */
                window.addEventListener('message', function(e){
                        // 获取消息识别号
                        let serialId = e.data.serialId;
                        if(!window.temp_response_localstorage_iframe_all_functions || undefined == window.temp_response_localstorage_iframe_all_functions ){
                          // 没有函数,直接停止
                            return;
                        }
                          // 获取流水号对应的函数进行回调
                        let callback = window.temp_response_localstorage_iframe_all_functions[serialId];
                        if(callback){
                          // 删除回调
                          window.temp_response_localstorage_iframe_all_functions[serialId] = undefined;
                          // 执行回调
                          callback(e.data);
                        }
                    }, false);
                /**
                * 提供跨域的公共能方法
                */
              function sendFrameLocalStorage(data,callback){
                     // 创建流水号
                      let serialId="sendFramMessage"+Date.now()+"-"+Math.random().toString(36).slice(-8);
                      let form = {"serialId": serialId};
                       // 将数据与默认数据合并
                      Object.assign(form, data);
    
                      if (callback){
                        //  创建默认保存回调的字典
                        if (!window.temp_response_localstorage_iframe_all_functions){
                          window.temp_response_localstorage_iframe_all_functions = {};
                        }
                        // 将回调存起来
                        window.temp_response_localstorage_iframe_all_functions[serialId] = callback;
                      }
                      // 发送消息
                      var ifr = document.querySelector('#ifr_localStorage');
                      ifr.contentWindow.postMessage(form, '*');
              }
              /**
              * 提供跨域的公共能方法
              */
            function readFrameLocalStorage(names,callback){
                  if(!names){
                    callback({});
                    return;
                  }
                   // 创建流水号
                    var data = {"method":"get"};
                    if(Array.isArray(names)){
                        // 如果是字符串数组
                        data["names"]=names;
                    }else{
                        // 只是普通的数组
                        data["name"]=names;
                    }
                    sendFrameLocalStorage(data,callback);
            }
            /**
            * 提供跨域的公共能方法
            */
          function saveFrameLocalStorage(obj,callback){
                if(!obj){
                  callback({});
                  return;
                }
                 // 创建流水号
                  var data = {"method":"save"};
                  data["obj"] = obj;
                  sendFrameLocalStorage(data,callback);
          }
          /**
          * 提供跨域的公共能方法
          */
        function removeFrameLocalStorage(names,callback){
              if(!names){
                callback({});
                return;
              }
               // 创建流水号
                var data = {"method":"remove"};
                if(Array.isArray(names)){
                    // 如果是字符串数组
                    data["names"]=names.join(",");
                }else{
                    // 只是普通的数组
                    data["name"]=names;
                }
                sendFrameLocalStorage(data,callback);
        }
    
    
              /**
              * 提供创建随机数的方法
              */
              function randomString() {
                var length=32;
                var chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                var result = '';
                for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
                return result+Date.now();
            }
          </script>
    
        <script type="text/javascript">
    
    
          window.onload = function(){
              // 查看是否有客户端唯一号
                initClient(function(){
                  readItem();
                });
           }
           function initClient(func){
             readFrameLocalStorage("deviceId",function(data){
               if(!data.deviceId){
                 var rString = randomString();
                 saveFrameLocalStorage({"deviceId":rString},function(){
                   window.deviceId = rString;
                   func();
                 });
               }else{
                 window.deviceId = data.deviceId;
                 func();
               }
             });
           }
          function readItem(){
            readFrameLocalStorage("deviceId",function(data){
              console.log(">>>>>>>>");
              console.log(data);
              if(data.deviceId && "undefined" != data.deviceId){
                var oldVal = document.getElementById("txt1").value;
                oldVal = oldVal + "+++++拿到了deviceId+++++\n"
                oldVal = oldVal + data.deviceId+"\n"
                document.getElementById("txt1").value=oldVal;
                console.log("+++++拿到了deviceId+++++");
                console.log(data.deviceId);
              }else{
                var oldVal = document.getElementById("txt1").value;
                oldVal = oldVal + "--------没有deviceId-------\n"
                document.getElementById("txt1").value=oldVal;
                console.log("--------没有deviceId-------")
              }
            });
          }
          function saveItem(){
            var oldVal = document.getElementById("txt1").value;
            oldVal = oldVal + "324750389qwer saved By A\n"
            document.getElementById("txt1").value=oldVal;
            saveFrameLocalStorage({"deviceId":"324750389qwer saved By A"},function(){
            });
          }
          function deleteItem(){
            var oldVal = document.getElementById("txt1").value;
            oldVal = oldVal + "remove deviceId By A\n"
            document.getElementById("txt1").value=oldVal;
            removeFrameLocalStorage("deviceId",function(){
            });
          }
        </script>
    
        </body>
      </html>
    
    
    
    

    用于临时交互保存的X网站temp.html
    http://xxxx/temp.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="0">
    </head>
          <script type="text/javascript">
            window.addEventListener('message', function(e){
                // console.log('B get message from A ' );
                // console.log(e.data)
                let form = {"serialId": e.data.serialId,"method":e.data.method};
                if(e.data.method == "get"){
    
                      // console.log("B send message begin");
                      // console.log(e.data);
                      let responseData = {};
                      if(e.data.name){
                        var saveVal = window.localStorage[e.data.name];
                        if(saveVal && undefined != saveVal && "undefined" != saveVal){
                          responseData[e.data.name] = saveVal;
                        }else{
                          responseData[e.data.name] = undefined;
                        }
                      }
                      if(e.data.names){
                        for (var i in e.data.names){
                          let name = e.data.names[i]
                          // console.log(name);
                          var saveVal = window.localStorage[name];
                          // responseData[name] = saveVal;
                          if(saveVal && undefined != saveVal && "undefined" != saveVal){
                            responseData[name] = saveVal;
                          }else{
                            responseData[name] = undefined;
                          }
                        }
    
                      }
    
                      Object.assign(form, responseData);
                      e.source.postMessage(form, '*');
                }else if (e.data.method == "save") {
                  let obj = e.data.obj;
                  Object.keys(obj).forEach(function(key){
                     window.localStorage[key]=obj[key];
                });
    
                    let responseData = obj;
                    // console.log("B send message begin");
                    Object.assign(form, responseData);
                    e.source.postMessage(form, '*');
                }else if (e.data.method == "remove") {
                    window.localStorage.removeItem(e.data.name);
                    if(e.data.names){
                      for (var i in e.data.names){
                        let name = e.data.names[i]
                        window.localStorage.removeItem(name);
                      }
                  }
                    let responseData = {};
                    // console.log("B send message begin");
                    Object.assign(form, responseData);
                    e.source.postMessage(form, '*');
                }else{
                  // console.log("B send message begin");
                  let responseData = {};
                  Object.assign(form, responseData);
                  e.source.postMessage(form, '*');
                }
    
            }, false);
          </script>
      </html>
    
    
    

    相关文章

      网友评论

          本文标题:JavaScript跨域共享本地localStorage数据

          本文链接:https://www.haomeiwen.com/subject/epaiectx.html