访问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
到假和不包含的getter也不二传手,而且也不__lookupGetter__
或__lookupSetter__
。所以我还没有找到一种方法来在Safari中覆盖document.cookie
(OS X和iOS 9.0.2上的8.0.8)。 WebKit每晚的行为与Safari相同,所以它似乎不会很快得到修复。