Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension's persistent cookies not expiring correctly?

Summary:

Basically, I'm using a background page to listen to events, such as: onStartup, onInstalled and cookies.onChanged to decide which page should be displayed to the user when the browserAction is clicked. My question regards the latter and how it is triggered.


Code sample:

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

The thing is, although the code above handles explicit calls just fine (cookies.set & cookies.get), it doesn't seem to trigger when a cookie life-span expires..

From the debugging sessions I conducted, the code is only triggered when a explicit call is made after the cookie's expected expiration date.

E.g. if I make a call like cookies.getAll() after the supposed expiration time, the browser realizes that the cookie has expired and only then the event is triggered.

Did I miss anything ? Can anyone please enlighten me if I'm misusing the cookies API or if I misunderstood the mechanic behind it ?

Any help is greatly appreciated !

Best regards,

like image 604
ErickR Avatar asked Nov 09 '22 18:11

ErickR


1 Answers

For rare actions such as opening the 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, because:

  1. If your observed bug is real, then this will work around it.
  2. Since the popup is not opened very often, it's quite a waste of resources to keep a background/event page alive merely to get notified of cookie changes, especially given the alternative method presented in this answer.

Example (popup.js, requires activeTab and cookies permission):

// 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).
    });
});
like image 180
Rob W Avatar answered Nov 14 '22 21:11

Rob W