0

I would like to know how to define a getter for default objects like document.cookie.

document.__defineGetter__("cookie", function(newv) {
   console.log('accessing cookie'); 
  //what to return here??
 });

Returning document.cookie obviously causes a recursion.
Thanks

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
everconfusedGuy
  • 2,709
  • 27
  • 43

2 Answers2

3

Try something like this -

var old_cookie = document.cookie;

Object.defineProperty(document, 'cookie', {
    get: function() {
        console.log('Getting cookie');
        return this._value;
    },
    set: function(val) {
        console.log('Setting cookie', arguments);
        this._value = val;
        return this._value;
    }
});

document.cookie = old_cookie;

When you add getters/setters to the cookie property, it wipes away the value because descriptors cannot have both accessors and a value, so you have to save the old cookie value and re-assign it after you define the accessors.

billy
  • 531
  • 1
  • 4
  • 8
0

Try this:

Chrome

var desc = Object.getOwnPropertyDescriptor(document, 'cookie');

return desc.value;

However, I'm not sure if this will reflect updates.

Firefox, IE 10

var getter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(document), 'cookie').get.bind(document)

return getter();

This should work perfectly.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964