訪問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相同,所以它似乎不會很快得到修復。