簡體   English   中英

代理 document.cookie

[英]Proxying of document.cookie

我需要記錄 document.cookie 的設置。 我不能僅使用document.cookie = {...}重新定義 cookie 屬性,所以我需要為 document.cookie 獲取 setter。 但是Object.getOwnPropertyDescriptor(document, "cookie")返回undefined

更新。 在編寫問題時,我找到了一個__lookupGetter__解決方案,但它使用了已棄用的__lookupGetter____lookupSetter__方法。 有沒有不使用過時 API 的解決方案?

訪問 getter 和 setter 的標准化方法是使用Object.getOwnPropertyDescriptor ,但顧名思義,它只查看對象自己的屬性(它不查找原型鏈)。 documentHTMLDocument一個實例,它繼承自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);
        }
    });
}

諷刺的是,在最隱私有關的瀏覽器Safari瀏覽器,將描述符集configurablefalse,並且不包含吸氣也不二傳手,而且也不__lookupGetter____lookupSetter__ 所以我還沒有找到在 Safari 中覆蓋document.cookie的方法(OS X 和 iOS 9.0.2 上的 8.0.8)。 WebKit nightly 的行為方式與 Safari 相同,因此它似乎不會很快得到修復。

2019 年 10 月更新:在 MacOS Mojave 上的 Safari 12.1.2 中測試了上述代碼,現在可以配置cookieDesk 這意味着我從 2015 年開始的概念證明document.cookie保護現在可能真的有效:)

在我寫問題時,我發現下一個代碼解決了我的問題:

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);
  }
});

但我不喜歡使用過時的方法,所以我希望有更好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM