Last active
December 20, 2015 09:49
-
-
Save Yaffle/6110421 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
var whiteList = ["http://localhost", "http://hostel6.ru", "http://yandex.ru"]; | |
window.addEventListener("message", function (e) { | |
var origin = e.origin; | |
var i = whiteList.length; | |
var ok = false; | |
while (--i >= 0) { | |
if (whiteList[i] === origin) { | |
ok = true; | |
} | |
} | |
if (!ok) { | |
return; | |
} | |
var command = JSON.parse(e.data); | |
if (command[1] === "getItem") { | |
e.source.postMessage(JSON.stringify([command[0], localStorage.getItem.apply(localStorage, command.slice(2))]), "*"); | |
} | |
if (command[1] === "setItem") { | |
localStorage.setItem.apply(localStorage, command.slice(2)); | |
e.source.postMessage(JSON.stringify([command[0]]), "*"); | |
} | |
}, false); | |
window.parent.postMessage("ready", "*"); | |
</script> | |
function RemoteLocalStorage(iframeSrc) { | |
var iframe = document.createElement("iframe"); | |
iframe.src = iframeSrc; | |
document.documentElement.appendChild(iframe); | |
var requests = {}; | |
var iframeWindow = iframe.contentWindow; | |
var that = this; | |
this.ready = false; | |
window.addEventListener("message", function (e) { | |
if (e.source === iframeWindow) { | |
if (e.data === "ready") { | |
that.ready = true; | |
return; | |
} | |
var data = JSON.parse(e.data); | |
var requestId = data[0]; | |
if (requests[requestId]) { | |
requests[requestId].apply(null, data.slice(1)); | |
delete requests[requestId]; | |
} | |
} | |
}, false); | |
this.iframeWindow = iframeWindow; | |
this.requests = requests; | |
} | |
RemoteLocalStorage.counter = Math.floor(Math.random() * Math.pow(2, 30)); | |
RemoteLocalStorage.prototype = { | |
_request: function (callback) { | |
var args = Array.prototype.slice.call(arguments); | |
if (!this.ready) { | |
var that = this; | |
setTimeout(function () { | |
that._request.apply(that, args); | |
}, 50); | |
return; | |
} | |
var requestId = ++RemoteLocalStorage.counter; | |
this.requests[requestId] = callback; | |
var x = Array.prototype.slice.call(arguments); | |
x[0] = requestId; | |
this.iframeWindow.postMessage(JSON.stringify(x), "*"); | |
}, | |
get: function (key, callback) { | |
this._request(callback, "getItem", key); | |
}, | |
set: function (key, value, callback) { | |
this._request(callback, "setItem", key, value); | |
} | |
}; | |
var x = new RemoteLocalStorage("/webclient/core/util/iframe.html"); | |
var v = Math.random(); | |
x.set("key", v, function (value) { | |
x.get("key", function (value) { | |
alert("key = " + value + ", should be = " + v); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment