Skip to content Skip to sidebar Skip to footer

Defining A Getter For Document.cookie

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'); /

Solution 1:

Try something like this -

var old_cookie = document.cookie;

Object.defineProperty(document, 'cookie', {
    get: function() {
        console.log('Getting cookie');
        returnthis._value;
    },
    set: function(val) {
        console.log('Setting cookie', arguments);
        this._value = val;
        returnthis._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.

Solution 2:

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)

returngetter();

This should work perfectly.

Post a Comment for "Defining A Getter For Document.cookie"