我需要记录document.cookie的设置。我无法使用document.cookie = {...}
重新定义cookie属性所以我需要获取document.cookie的setter。但Object.getOwnPropertyDescriptor(document, "cookie")
会返回undefined
。
UPD。在我撰写问题时,我发现了一个有效的解决方案,但它使用了弃用的__lookupGetter__
和__lookupSetter__
方法。有没有解决方案没有使用过时的API?
答案 0 :(得分:4)
访问getter和setter的标准化方法是使用Object.getOwnPropertyDescriptor
,但顾名思义,它只查看对象自己的属性(它不会查找原型链)。 document
是HTMLDocument
的一个实例,它继承自Document
。在Chrome,Safari,Opera和IE中,cookie
属性在Document.prototype
上定义,而在Firefox中则定义在HTMLDocument.prototype
。
var cookieDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') ||
Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie');
if (cookieDesc && cookieDesc.configurable) {
Object.defineProperty(document, 'cookie', {
get: function () {
return cookieDesc.get.call(document);
},
set: function (val) {
console.log(val);
cookieDesc.set.call(document, val);
}
});
}
具有讽刺意味的是,在最隐私的浏览器Safari中,描述符已将configurable
设置为 false ,并且不包含getter或setter,__lookupGetter__
或__lookupSetter__
。所以我还没有找到在Safari中覆盖document.cookie
的方法(OS X和iOS 9.0.2上的8.0.8)。 WebKit每晚的行为方式与Safari相同,所以它似乎不会很快得到修复。
答案 1 :(得分:0)
当我写这个问题时,我发现下一个代码解决了我的问题:
var cookie_setter_orig = document.__lookupSetter__("cookie").bind(document);
var cookie_getter_orig = document.__lookupGetter__("cookie").bind(document);
Object.defineProperty(document, "cookie", {
get: function () {
return cookie_getter_orig();
},
set: function (val) {
console.log(val);
cookie_setter_orig(val);
}
});
但我不喜欢使用弃用的方法,所以我希望有更好的解决方案。