代理document.cookie

时间:2015-09-05 06:47:59

标签: javascript cookies proxy javascript-objects

我需要记录document.cookie的设置。我无法使用document.cookie = {...}重新定义cookie属性所以我需要获取document.cookie的setter。但Object.getOwnPropertyDescriptor(document, "cookie")会返回undefined

UPD。在我撰写问题时,我发现了一个有效的解决方案,但它使用了弃用的__lookupGetter____lookupSetter__方法。有没有解决方案没有使用过时的API?

2 个答案:

答案 0 :(得分:4)

访问getter和setter的标准化方法是使用Object.getOwnPropertyDescriptor,但顾名思义,它只查看对象自己的属性(它不会查找原型链)。 documentHTMLDocument的一个实例,它继承自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);
  }
});

但我不喜欢使用弃用的方法,所以我希望有更好的解决方案。