Change the value of window.localStorage in JavascriptCore (redefining un-configurable property from C/Obj-C APIs)

1.1k Views Asked by At

The WebKit framework in OSX has a broken localStorage implementation which doesn't persist stored data (data isn't there after application restart).

So i've implemented an alternative LocalStorage object.

However, I can't assign window.localStorage = myLocalStorage because localStorage is defined as non-writeable, and non-configurable.

I can't find a way to override such property in JavascriptCore, by using the C/Obj-C APIs. Is there a way to do that?

1

There are 1 best solutions below

4
On

You can't override it directly but you can use StorageItem to override it. But over-ridding storage item will override both session storage and localStorage

var _setItem = Storage.prototype.setItem; // first assign it to some variable
Storage.prototype.setItem = function(key, value) { 
   if (this === window.localStorage) {
     // play with localstorage here
   } else {
     // fallback
     _setItem.apply(this, arguments);
   }
}

Second ways is to override with __proto__ property but this is not standard, it is supported in firefox, chrom, opera not sure about others

localStorage.__proto__ = Object.create(Storage.prototype);

Check this example where they have wriiten to override default to store JSON objects

https://gist.github.com/danott/942522