1. 程式人生 > >CEF3 獲取Cookie例子 CefCookieManager C++

CEF3 獲取Cookie例子 CefCookieManager C++

sch {} 數據 通過 所有 virt urn color 引用計數

首先從cef_cookie.h 源碼中看到CefCookieManager 這個類:

  // Visit all cookies on the IO thread. The returned cookies are ordered by
  // longest path, then by earliest creation date. Returns false if cookies
  // cannot be accessed.
  ///
  /*--cef()--*/
  virtual bool VisitAllCookies(CefRefPtr<CefCookieVisitor> visitor) =0;

  ///
  // Visit a subset of cookies on the IO thread. The results are filtered by the
  // given url scheme, host, domain and path. If |includeHttpOnly| is true
  // HTTP-only cookies will also be included in the results. The returned
  // cookies are ordered by longest path, then by earliest creation date.
  // Returns false if cookies cannot be accessed.
  ///
  /*--cef()--*/
  virtual bool VisitUrlCookies(const CefString& url,
                               bool includeHttpOnly,
                               CefRefPtr<CefCookieVisitor> visitor) =0;

 1 class CefCookieVisitor : public virtual CefBase {
 2  public:
 3   ///
 4   // Method that will be called once for each cookie. |count| is the 0-based
 5   // index for the current cookie. |total| is the total number of cookies.
 6   // Set |deleteCookie| to true to delete the cookie currently being visited.
7 // Return false to stop visiting cookies. This method may never be called if 8 // no cookies are found. 9 /// 10 /*--cef()--*/ 11 virtual bool Visit(const CefCookie& cookie, int count, int total, 12 bool& deleteCookie) =0; 13 };

可以通過VisitAllCookies獲取所有cookies;VisitUrlCookies獲取域名下的所有cookies。

看到VisitUrlCookies的參數是CefCookieVisitor;所以實現一個類用於回調讀取cookies;

class CCookieVisitor : public CefCookieVisitor
{
public:
    CCookieVisitor() {};
    ~CCookieVisitor() {};

    bool Visit(const CefCookie& cookie, int count, int total,
        bool& deleteCookie);
    //這是一個宏 
    //所有的框架類從CefBase繼承,實例指針由CefRefPtr管理,CefRefPtr通過調用AddRef()和Release()方法自動管理引用計數。
    IMPLEMENT_REFCOUNTING(CookieVisitor);
};        
//作為類的成員變量
CefRefPtr<CCookieVisitor> m_CookieVisitor; m_CookieVisitor(new CCookieVisitor());

 //以下代碼執行 即回調Visit

 CefRefPtr<CefCookieManager> cefCookieManager = CefCookieManager::GetGlobalManager(nullptr);

if (cefCookieManager)
{
  cefCookieManager->VisitUrlCookies(url ,true , m_visitor);
}

回調進行讀取,count為當前cookie total為總數。具體看CefCookieVisitor的註釋,接下來便可以Visit讀取到數據

 1 bool CookieVisitor::Visit(const CefCookie & cookie, int count, int total, bool & deleteCookie)
 2 {
 3     if (count == total)
 4     {
 5         return false;
 6     }
 7     if (cookie.name.str && cookie.value.str)
 8     {
 9         string strName = cookie.name.str;
10         string strValue = cookie.value.str;
11     }
12     return true;
13 }

結束!

CEF3 獲取Cookie例子 CefCookieManager C++