代理document.cookie [英] Proxying of document.cookie
问题描述
我需要记录document.cookie的设置。我不能仅使用 document.cookie = {...}
重新定义cookie属性,因此我需要获取document.cookie的setter。但是 Object.getOwnPropertyDescriptor(document, cookie)
返回 undefined
。
I need to log setting of document.cookie. I can not redefine cookie property just with document.cookie = {...}
So I need to get setter for document.cookie. But Object.getOwnPropertyDescriptor(document, "cookie")
returns undefined
.
UPD。当我写问题时,我找到了一个可行的解决方案,但是它使用了不推荐使用的 __ lookupGetter __
和 __ lookupSetter __
方法。有没有不使用过时的API的解决方案?
UPD. While I was writing the question I found a working solution, but it uses deprecated __lookupGetter__
and __lookupSetter__
methods. Is there any solution which doesn't use obsolete API?
推荐答案
访问getter和setter的标准化方法是使用 Object.getOwnPropertyDescriptor
,但顾名思义,它仅查看对象自身的属性(不查找原型链)。 document
是 HTMLDocument
的实例,该实例继承自 Document
。在现代浏览器中, cookie
属性是在 Document.prototype
上定义的,而在旧版本的Firefox中,它是在 HTMLDocument.prototype
。
The standardized way of accessing getters and setters is with Object.getOwnPropertyDescriptor
, but as the name suggests, it only looks on the objects own properties (it does not look up the prototype chain). document
is an instance of HTMLDocument
, which inherits from Document
. In modern browsers the cookie
property is defined on Document.prototype
, whereas in older versions of Firefox it is defined on 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中,描述符已将 可配置
设置为 false ,并且不包含getter或setter,并且 __ lookupGetter __
或 __ lookupSetter __
。因此,我还没有找到在Safari中覆盖 document.cookie
的方法(在OS X和iOS 9.0.2上为8.0.8)。 WebKit每晚的行为与Safari相同,因此它似乎不会很快得到修复。
Ironically, in the most privacy-concerned browser Safari, the descriptor has set configurable
to false and does not contain the getter nor setter, and neither does __lookupGetter__
or __lookupSetter__
. So I haven't found a way to override document.cookie
in Safari yet (8.0.8 on OS X and iOS 9.0.2). WebKit nightly acts the same way as Safari, so it doesn't seem to get fixed anytime soon.
2019年10月更新:在MacOS Mojave上的Safari 12.1.2中测试了上面的代码,现在可以配置 cookieDesk
了!这表示我的概念证明 document.cookie
保护从2015年开始可能实际上已经可以使用:)
Update October 2019: Tested the above code in Safari 12.1.2 on MacOS Mojave, and cookieDesk
is now configurable! This means my proof of concept document.cookie
protection from 2015 might actually work now :)
这篇关于代理document.cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!