一起学libcef--给你的浏览器设置cookie

来源:互联网 发布:daogrs知乎 编辑:程序博客网 时间:2024/05/16 07:33

很久没写关于libcef的文章了,因为自己理解的非常浅薄。

我们知道浏览器有记住密码功能,就是登陆后,再次输入域名就可以直接登陆。很多时候是通过cookie来实现的。

对于一个没接触过web的人,也许不理解何为cookie?

Cookie,有时也用其复数形式Cookies,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。

比如说,我们create一个browser,并导航到http://blog.csdn.net/网站,然后可以进行登陆等操作。

但是如果我们给browser事先设置好一些cookie,比如username userinfo等。这样再进行访问http://blog.csdn.net/的时候,cef浏览器就会读取cookie中的信息,然后显示的http://blog.csdn.net/主页是登录状态的。

所以,接下来的问题就是如何为cef设置cookie?

是在createbrowser前还是createbrowser之后呢?

答案是之前。

首先假设 cookie的格式:
username = xidada

直接上代码了:

    std::wstring username_key = L"username";    std::wstring username_value = L"xidada";    std::wstring domain = L"blog.csdn.net"    CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();    CefCookie cookie;    CefString(&cookie.name).FromWString(username_key.c_str());    CefString(&cookie.value).FromWString(username_value.c_str());    CefString(&cookie.domain).FromWString(domain.c_str());    CefString(&cookie.path).FromASCII("/");    cookie.has_expires = false;    domain = L"https://" + domain;    CefPostTask(TID_IO, NewCefRunnableMethod(manager.get(), &CefCookieManager::SetCookie,CefString(domain.c_str()), cookie));//创建浏览器    CefBrowserHost::CreateBrowser(info, g_web_browser_client.get(),        domain.c_str(), browserSettings, NULL);

这里需要注意的是,cookie.domain是不带”https://”的,而CefString(domain.c_str())中的domain是带”https://“的,一定要注意。

下面看看setcookie的英文文档:
SetCookie

public virtual bool SetCookie( const CefString& url, const CefCookie& cookie, CefRefPtr< CefSetCookieCallback > callback )= 0;

Sets a cookie given a valid URL and explicit user-provided cookie attributes. This function expects each attribute to be well-formed. It will check for disallowed characters (e.g. the ‘;’ character is disallowed within the cookie value attribute) and fail without setting the cookie if such characters are found. If |callback| is non-NULL it will be executed asnychronously on the IO thread after the cookie has been set. Returns false if an invalid URL is specified or if cookies cannot be accessed.

下面看看setcookie的英文文档:
CreateManager

public static CefRefPtr< CefCookieManager > CreateManager( const CefString& path, bool persist_session_cookies, CefRefPtr< CefCompletionCallback > callback );

Creates a new cookie manager. If |path| is empty data will be stored in memory only. Otherwise, data will be stored at the specified |path|. To persist session cookies (cookies without an expiry date or validity interval) set |persist_session_cookies| to true. Session cookies are generally intended to be transient and most Web browsers do not persist them. If |callback| is non-NULL it will be executed asnychronously on the IO thread after the manager’s storage has been initialized.

1 0
原创粉丝点击