1. 程式人生 > >localstorage跨域解決方案

localstorage跨域解決方案

localstorage也存在 跨域的問題,

【解決思路如下】

在A域和B域下引入C域,所有的讀寫都由C域來完成,本地資料存在C域下;

因此 A哉和B域的頁面必定要引入C域的頁面; 當然C域最好是主域,原因後面會提到(在localstorage 不方便的情況下使用cookie);

【A域】【B域】需要讀寫時,通過postMessage 向【C域】傳送跨哉訊息,

【C域】監聽跨域訊息,在接到批定的訊息時進行讀寫操作,

【C域】接到跨域訊息時,如果是寫入刪除可以不做什麼,如果是讀取,就要先讀取本域本地資料通過postMessage向父頁面傳送訊息,

【A 域 / B 域】在讀取【C域】資料時就需要監聽來自【C域】的跨域訊息

【注意事項】

window.postMessage()方法,向【C域】發訊息,應用iframe.contentWindow.postMessage() 這樣iframe內的【C 域】才可以接到,

同理,【C域】向 【A 域B域】發訊息時應用,window.parent.postMessage()

【A域、B域】的邏輯一定要在iframe 載入完成後進行

【C域】的頁面如下:

根據域名請自行修改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"
> <meta name="robots" content="noindex"> <title>cross domain</title> </head> <body> <script> ;(function(doc,win,undefined){ var fn=function(){}; fn.prototype={ /*本地資料儲存*/ setLocalCookie: function (k, v, t,domain) { typeof
window.localStorage !== "undefined" ? localStorage.setItem(k, v) : (function () { t = t || 365 * 12 * 60 * 60; domain=domain?domain:".hc360.com"; document.cookie = k + "=" + v + ";max-age=" + t+";domain="+domain+";path=/"; })() }, getLocalCookie: function (k) { k = k || "localDataTemp"; return typeof window.localStorage !== "undefined" ? localStorage.getItem(k) : (function () { var all = document.cookie.split(";"); var cookieData = {}; for (var i = 0, l = all.length; i < l; i++) { var p = all[i].indexOf("="); var dataName = all[i].substring(0, p).replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""); cookieData[dataName] = all[i].substring(p + 1); } return cookieData[k] })(); }, clearLocalData: function (k) { k = k || "localDataTemp"; typeof window.localStorage !== "undefined" ? localStorage.removeItem(k) : (function () { document.cookie = k + "=temp" + ";max-age=0"; })() }, init:function(){ this.bindEvent(); }, bindEvent:function(){ var _this=this; win.addEventListener("message",function(evt){ if(win.parent!=evt.source){return} var options=JSON.parse(evt.data); if(options.type=="GET"){ var data=tools.getLocalCookie(options.key); win.parent.postMessage(data, "*"); } options.type=="SET"&&_this.setLocalCookie(options.key,options.value); options.type=="REM"&&_this.clearLocalData(options.key); },false) } }; var tools=new fn(); tools.init(); })(document,window); </script> </body> </html>

【A域、B域 讀取操作】

【寫】

iframe.contentWindow.postMessage(JSON.stringify({type:"SET",key:"key",value:"value"}),'http://www.C.com');
【讀】

iframe.contentWindow.postMessage(JSON.stringify({type:"GET",key:"key"}),'http://www.C.com');
【刪】

iframe.contentWindow.postMessage(JSON.stringify({type:"REM",key:"key"}),'http://www.C.com');