Chrome 扩展程序的持久性 cookie 没有正确过期?

Chrome Extension's persistent cookies not expiring correctly?

总结:

基本上,我使用后台页面来侦听事件,例如:onStartup、onInstalled 和 cookies.onChanged 来决定在单击 browserAction 时应向用户显示哪个页面。我的问题是关于后者及其触发方式。


代码示例:

chrome.cookies.onChanged.addListener(function(info){
    if(info.cookie.name === "dummycookie"){
        /*  Possibilities of info.cause (as described in the docs):
        *       evicted
        *       expired
        *       explicit (it's used when setting or removing a cookie)
        *       expired_overwrite
        *       overwrite
        */
        if(info.cause == "overwrite" || (info.cause == "explicit" && !info.removed)){
            // Cookie was set (explicit or overwrite)
            chrome.browserAction.setPopup({ popup: "dummy1.html" });
        }
        else{
            // Cookie was removed (evicted, expired or expired_overwrite)
            chrome.browserAction.setPopup({ popup: "dummy2.html" });
        }
    }
});

问题是,虽然上面的代码可以很好地处理显式调用(cookies.set & cookies.get),但它似乎不会在 cookie 生命周期到期时触发..

根据我进行的调试会话,只有在 cookie 的预期到期日期之后进行显式调用时才会触发代码。

例如如果我在假定的过期时间后进行 cookies.getAll() 之类的调用,浏览器就会意识到 cookie 已过期,然后才会触发事件。

我错过了什么吗?如果我滥用 cookies API 或者我误解了它背后的机制,谁能告诉我?

非常感谢任何帮助!

此致,

对于罕见的操作,例如打开 browser action popup, you'd better actively query the cookies API for the latest state of the relevant cookie, instead of listening for cookie changes via the chrome.cookies.onChanged,因为:

  1. 如果您观察到的错误是真实的,那么这将解决它。
  2. 由于弹出窗口不经常打开,因此让 background/event 页面保持活动状态只是为了获得 cookie 更改的通知是一种资源浪费,特别是考虑到此答案中提供的替代方法。

示例(popup.js,需要 activeTab 和 cookie 许可):

// Example: Get the value of the _gaq cookie for the top-level frame of the
// current tab.
chrome.tabs.query({
    active: true,
    currentWindow: true
}, function(tabs) {
    // Need activeTab permission to read url, e.g. http://example.com/home
    var url = tabs[0].url;
    chrome.cookies.get({
        url: url,
        name: '_gaq'
    }, function(cookie) {
        // TODO: Do something with cookie, e.g. by updating the view (via DOM).
    });
});