Search code examples
c#cookiescefsharp

CEFSharp with 2 browser instances and need to delete cookies separately


I have 2 WinForms, each with its own browser instance. Everything is working great but I cant seem to figure out how to clear the cookies for the chosen instance instead of globally.

To set the cache folder

var requestContextSettings1 = new RequestContextSettings
{
    CachePath = System.IO.Path.GetFullPath("DesktopCache") // Path to the cache folder
};
var requestContext1 = new RequestContext(requestContextSettings1);

and

var requestContextSettings2 = new RequestContextSettings
{
    CachePath = System.IO.Path.GetFullPath("MobileCache") // Path to the cache folder
};
var requestContext2 = new RequestContext(requestContextSettings2);
public void ClearBrowserCache()
{
    var requestContext = Cef.GetGlobalRequestContext();
    if (requestContext != null)
        {
        var cookieManager = requestContext.GetCookieManager(null);
        if (cookieManager != null)
        {
            cookieManager.DeleteCookies("", "", new DeleteCookiesCallback());
        }
    }
}

I know the above code gets the global requestcontext, I am just giving an example of what does work globally.

Next I tried something like

var cookieManager = browser.GetCookieManager();
cookieManager.DeleteCookiesAsync();

I even tried deleting the cache folder. Deleting the cache folder didnt seem to clear the session/memory cookies.

Again, seemed to have cleared cookies for both instances. I know this is something simple I am missing. Any chance someone know what it is?


Solution

  • My problem had something to do with how I was setting the cache file for each RequestContext.

    Here is an example of the code that works for me.

        private RequestContext requestContext1;
        private string cachePath1;
    
        public frmBrowser()
        {
            InitializeComponent();
    
            Text = title;
            WindowState = FormWindowState.Maximized;
    
            // Set cache path
            cachePath1 = System.IO.Path.GetFullPath("DesktopCache");
            InitializeBrowser();
        }
    
        private void InitializeBrowser()
        {
            var requestContextSettings1 = new RequestContextSettings
            {
                CachePath = cachePath1
            };
            requestContext1 = new RequestContext(requestContextSettings1);
            Console.WriteLine(requestContext1 != null ? "RequestContext1 created successfully." : "Failed to create RequestContext1.");
    
            browser = new ChromiumWebBrowser("accounts.pch.com/login", requestContext: requestContext1);
            Console.WriteLine(browser != null ? "Browser created successfully." : "Failed to create browser.");
    
            toolStripContainer.ContentPanel.Controls.Add(browser);
    
            browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
            browser.LoadingStateChanged += OnLoadingStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;
            browser.LoadError += OnBrowserLoadError;
            browser.FrameLoadEnd += Browser_FrameLoadEnd;
            browser.JavascriptMessageReceived += JSPostMessageEvents.OnBrowserJavascriptMessageReceived;
    
            var version = string.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}",
               Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
    
    #if NETCOREAPP
            var environment = string.Format("Environment: {0}, Runtime: {1}",
                System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(),
                System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
    #else
            var bitness = Environment.Is64BitProcess ? "x64" : "x86";
            var environment = String.Format("Environment: {0}", bitness);
    #endif
    
            DisplayOutput(string.Format("{0}, {1}", version, environment));
        }
    
        private void ClearCookies(IRequestContext requestContext, string url = "", string cookieName = "")
        {
            if (requestContext == null)
            {
                Console.WriteLine("RequestContext is null.");
                return;
            }
    
            var cookieManager = requestContext.GetCookieManager(null);
            if (cookieManager == null)
            {
                Console.WriteLine("CookieManager is null.");
                return;
            }
    
            var task = cookieManager.DeleteCookiesAsync(url, cookieName);
            task.ContinueWith(t =>
            {
                if (t.IsCompleted)
                {
                    Console.WriteLine("Cookies cleared for the given RequestContext.");
                }
                else
                {
                    Console.WriteLine("Failed to clear cookies: " + t.Exception?.Message);
                }
            });
        }
    

    Repeat code adjustments for mobile (2nd instance)

    Now the cache is being set properly and I am able to reset the cookies based off the RequestContext.

    If wondering, what I did is did a listcookie function which was printing nothing. Set a test cookie programmatically, and listcookies was listing the test cookie. This allowed me to realize my problem was how I was setting cache folder and hence tried this method to define the cache paths as class-level fields to ensure they are correctly referenced.