Delphi Berlin+CEF4Delphi:如何让TChromiumWindow记住Cookie选择?
针对你用Delphi Berlin + CEF4Delphi开发的谷歌地图应用,每次启动需重复确认Cookie的问题,按以下步骤配置即可实现选择记忆:
1. 初始化阶段指定缓存目录
CEF的Cookie和用户偏好默认存储在缓存目录中,必须在GlobalCefApp初始化时明确设置有效路径,且确保目录可写入:
var CacheDir: string; begin GlobalCefApp := TCefApplication.Create; // 用程序所在目录下的Cache文件夹存储缓存,也可改用用户文档目录避免权限问题 CacheDir := ExtractFilePath(ParamStr(0)) + 'Cache'; if not DirectoryExists(CacheDir) then CreateDir(CacheDir); GlobalCefApp.CachePath := CacheDir; // 必须指定正确的子进程路径,否则缓存无法写入 GlobalCefApp.BrowserSubprocessPath := ExtractFilePath(ParamStr(0)) + 'cefclient.exe'; if not GlobalCefApp.StartMainProcess then begin GlobalCefApp.Free; Exit; end; end;
2. 创建浏览器时配置持久化参数
调用CreateBrowser时,传入TCefRequestContextSettings结构体,开启会话Cookie和用户偏好的持久化:
var RequestCtxSettings: TCefRequestContextSettings; begin FillChar(RequestCtxSettings, SizeOf(TCefRequestContextSettings), 0); RequestCtxSettings.cache_path := PChar(CacheDir); RequestCtxSettings.persist_session_cookies := 1; // 持久化会话Cookie RequestCtxSettings.persist_user_preferences := 1; // 持久化Cookie选择等用户偏好 ChromiumWindow1.CreateBrowser(nil, '', @RequestCtxSettings); end;
3. 排查缓存为空的常见问题
- 子进程路径错误:确保
BrowserSubprocessPath指向CEF4Delphi提供的cefclient.exe或cefsimple.exe,缺少子进程会导致CEF无法写入缓存。 - 目录权限不足:如果程序安装在
Program Files等受保护目录,将缓存目录改为用户文档路径(如TPath.GetDocumentsPath + '\MyAppCache')。 - 旧缓存干扰:删除之前为空的缓存目录,重新启动应用让CEF生成新的缓存结构。
4. 验证Cookie管理器关联
若需手动操作Cookie,务必通过当前浏览器实例的RequestContext获取ICefCookieManager,而非全局实例:
var CookieManager: ICefCookieManager; begin if Assigned(ChromiumWindow1.Browser) then begin CookieManager := ChromiumWindow1.Browser.GetRequestContext.GetCookieManager(nil); // 可在此设置全局Cookie接受策略,例如允许所有站点Cookie CookieManager.SetCookie('', 'your_cookie_key=value', nil); end; end;
完成以上配置后,应用会将Cookie选择和相关偏好写入指定缓存目录,下次启动时自动读取,无需重复确认。
内容的提问来源于stack exchange,提问作者Lorne Anderson
相关产品推荐
相关产品推荐

