Retrieving Document.cookie Getter And Setter
Solution 1:
The reason for
Object.getOwnPropertyDescriptor(document, 'cookie');
returning undefined is the way that getOwnPropertyDescriptor works: it does not traverse the prototype chain.
A global variable document contains object actually inheriting from Document.prototype:
Document.prototype.isPrototypeOf(document) // true
and does not own a property called "cookie", the Document.prototype does:
document.hasOwnProperty('cookie'); // false
Document.prototype.hasOwnProperty('cookie'); // true
A way to retrieve the descriptor of document.cookie is to retrieve the descriptor of Document.prototype.cookie itself:
Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
Deprecated functions called __lookupGetter__ and __lookupSetter__ do actually traverse the prototype chain and therefore, you can retrieve these methods calling it on document, and not the Document.prototype:
const cookieDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
cookieDescriptor.get === document.__lookupGetter__('cookie') // true
Solution 2:
You can use __lookupSetter__
and __lookupGetter__
methods, but be warn that they are deprecated and not supported everywhere. They work properly in Chrome, Firefox, IE11. Don't work in IE<10. Opera provides such methods, but they seam to always return undefined
. Didn't check anything else.
Here is an example:
var cookieSetterOrig = document.__lookupSetter__("cookie");
var cookieGetterOrig = document.__lookupGetter__("cookie");
Object.defineProperty(document, "cookie", {
get: function () {
return cookieGetterOrig.apply(document);
},
set: function () {
return cookieSetterOrig.apply(document, arguments);
},
configurable: true
});
Solution 3:
Could someone explain me this behaviour?
document.cookie
is a property of a host object. Host objects are frequently not true JavaScript objects (called native objects) and are neither required nor guaranteed to have the features of JavaScript objects.
I'd be truly shocked, in fact, if many or even more than one or two browsers implemented document.cookie
using ES5 property getters/setters. Perhaps for some newer APIs (or perhaps not), but for one that old, there's going to be a lot of cruft about. (I'd also have to think a long time about the security ramifications...)
If they did implement it via ES5 getters/setters, it wouldn't surprise me if they made it a non-configurable property (e.g., such that you couldn't change it).
Post a Comment for "Retrieving Document.cookie Getter And Setter"