Joseph Joseph - 7 months ago 11
Javascript Question

Retrieving document.cookie getter and setter

I'm trying to override the document.cookie since i need to control cookie
creation, but seems that getOwnPropertyDescriptor casted on document.cookie doesn't retrieve its getter and setter ( tried on chrome and firefox ). Could someone explain me this behaviour?

https://jsfiddle.net/1363ktwp/7/



var obj={};

// creating a property using document.cookie descriptors
Object.defineProperty(
obj,
"oldCookie",
Object.getOwnPropertyDescriptor(document, "cookie")
);

// setting cookies succesfully
document.cookie="test1=ok;path=/;expires=365;";
document.cookie="test2=ok;path=/;expires=365;";

alert(document.cookie);

Object.defineProperty(document, "cookie", {
get: function () {
return obj.oldCookie;
},
set: function (cookie) {
/*
...preliminar operations
*/

obj.oldCookie = cookie;
}
});

// obj.oldCookie is just a string without getter/setter
// so assignments below doesn't works correctly
document.cookie="test3=ok;path=/;expires=365;";
document.cookie="test4=ok;path=/;expires=365;";

alert(document.cookie);




Answer

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).

Comments