bindiego
7/13/2016 - 12:09 PM

cross domain localstorage

cross domain localstorage

iframe src="http://mydomain/msg.html" name="myPostMessage" onload="document.getElementById('test').style.display='block';" style="display:none;"></iframe>
<button id="test" onclick="test();">Test</button>

<script>
function test() {
  LSsetItem('test', 'Test: ' + new Date());
  LSgetItem('test', function(value) {
    console.log('value: ' + value);
    //LSremoveItem('test');
  });
}

var domain = '*'; /*target*/
function LSsetItem(key, value) {
  var obj = {
    setItem: key,
    value: value
  };
  frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
}
var callbacks = {};
window.addEventListener('message', function(event) {
  if (event.source === frames['myPostMessage']) {
    console.log(event)
    var data = /^#localStorage#(\d+)(null)?#([\S\s]*)/.exec(event.data);
    if (data) {
      if (callbacks[data[1]]) {
        // null and "null" are distinguished by our pattern
        callbacks[data[1]](data[2] === 'null' ? null : data[3]);
      }
      delete callbacks[data[1]];
    }
  }
}, false);
function LSgetItem(key, callback) {
  var identifier = new Date().getTime();
  var obj = {
    identifier: identifier,
    getItem: key
  };
  callbacks[identifier] = callback;
    frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
}
function LSremoveItem(key) {
  var obj = {
    removeItem: key
  };
  frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
}
</script>
<script>
window.addEventListener('message', function(event) {
  console.log('Receiver debugging', event);
  if (event.origin != 'justademo') {
    var data = JSON.parse(event.data);
    if ('setItem' in data) {
      localStorage.setItem(data.setItem, data.value);
    } else if ('getItem' in data) {
      var gotItem = localStorage.getItem(data.getItem);
      // See below
      event.source.postMessage(
        '#localStorage#' + data.identifier +
        (gotItem === null ? 'null#' : '#' + gotItem),
        event.origin
      );
    } else if ('removeItem' in data) {
      localStorage.removeItem(data.removeItem);
    }
  }
}, false);
</script>