GlobalStorage, proof of concept

Using iFrame, postMessage and Greasemonkey to 'hijack' any domain.

by Benjol

HTML

<h2>GlobalStorage using iFrame, postMessage and userscript</h2>
<sub>(This demo requires the user-script contained in the comment at the bottom of the JavaScript pane)</sub>
<div id="data"></div>
<hr/>
<span>Key</span><input type="text" id="key"/><span>Value</span><input type="text"id="value"/>

<input type="button" id="save" value="Save"/>

CSS

body { font-family : tahoma }
h2 { font-weight: bold; border-bottom: 2px solid gray; margin-bottom:10px}
#data { border: 1px solid grey; min-height:20px; }
#hidden { display: none }

JavaScript

//See http://jsfiddle.net/ScQJg/8/ (and ancestors) for history
//http://www.nczonline.net/blog/2010/09/07/learning-from-xauth-cross-domain-localstorage/
//Declare GlobalStorage object and prototype
function GlobalStorage(origin, path, prefix) {
    this.origin = origin;
    this.path = path;
    this.prefix = prefix;
    this._iframe = null;
    this._iframeReady = false;
    this._queue = [];
    this._requests = {};
    this._id = 0;
    this._init();
}

GlobalStorage.prototype = {

    //restore constructor
    constructor: GlobalStorage,
    
    //public bits    
    getItem: function(key, callback) {
        var data = { key: prefix+key };
        this._sendCommand("getItem", data, callback);
    },

    setItem: function(key, val, callback) {
        var data = { key: prefix+key, value: val };
        this._sendCommand("setItem", data, callback);
    },

    removeItem: function(key, callback) {
        var data = { key: prefix+key };
        this._sendCommand("removeItem", data, callback);
    },

    getAll: function(pattern, callback) {
        var data = { pattern: pattern };
        this._sendCommand("getAll", data, callback);
    },

    //private bits
    _init: function() {
      var that = this; 
      if(!this._iframe) {
        if(window.postMessage && window.JSON && window.localStorage) {
          this._iframe = document.createElement("iframe");
          this._iframe.style.cssText = "position:absolute; width: 1px; height:1px; left:-9999px;";
          document.body.appendChild(this._iframe);

          if (window.addEventListener){
              this._iframe.addEventListener("load", function(){ that._iframeLoaded(); }, false);
              window.addEventListener("message", function(event){ that._handleMessage(event); }, false);
          } else if (this._iframe.attachEvent){
              this._iframe.attachEvent("onload", function(){ that._iframeLoaded(); }, false);
              window.attachEvent("onmessage", function(event){...