Vla*_*nko 3 javascript cookies proxy javascript-objects
我需要记录document.cookie的设置。我不能只用重新定义cookie属性,document.cookie = {...}所以我需要为document.cookie设置setter。但是Object.getOwnPropertyDescriptor(document, "cookie")回报undefined。
UPD。当我写问题时,我找到了一个可行的解决方案,但是它使用了弃用的__lookupGetter__和__lookupSetter__方法。有没有不使用过时的API的解决方案?
存取getter和setter的标准化方法是使用Object.getOwnPropertyDescriptor,但顾名思义,它仅查看对象自身的属性(不查询原型链)。document是的实例HTMLDocument,继承自Document。在现代浏览器中,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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
具有讽刺意味的是,在最关注隐私的浏览器Safari中,描述符已设置configurable为false,不包含getter或setter,__lookupGetter__或者或都没有__lookupSetter__。所以我还没有找到document.cookie在Safari中覆盖的方法(在OS X和iOS 9.0.2上为8.0.8)。WebKit每晚的行为与Safari相同,因此它似乎不会很快得到修复。
2019年10月更新:在MacOS Mojave的Safari 12.1.2中测试了上述代码,cookieDesk现在可以配置了!这意味着我从2015年起的概念document.cookie保护证明现在可能实际上已经起作用:)
| 归档时间: |
|
| 查看次数: |
1354 次 |
| 最近记录: |