基本上,我正在使用后台页面来监听事件,例如: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的预期到期日期之后进行显式调用时才会触发代码。
E.g。如果我在假定的到期时间之后进行了像cookies.getAll()这样的调用,浏览器会意识到cookie已经过期,然后才会触发事件。
我错过了什么吗?如果我误用了cookies API或者我误解了它背后的机制,有人可以请教我吗?
非常感谢任何帮助!
致以最诚挚的问候,
答案 0 :(得分:1)
对于诸如打开browser action popup之类的罕见操作,您最好主动query Cookie API以获取相关Cookie的最新状态,而不是通过{{3}监听Cookie更改因为:
示例(popup.js,需要chrome.cookies.onChanged
和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).
});
});