Access Webview2 Cookies in Code Only (No UI-Loaded browser control)

Robert Priest 31 Reputation points
2022-06-24T22:29:23.7+00:00

Hello,

I would like to access the cookies in a WebView2 profile. However, I would like to do this strictly in code. In my scenario, this will be done in the background, with no visual browser displayed anywhere in the GUI. I just need to pull out the cookies themselves, and interrogate them. There is no need to display a browser.

I have tried several things and searched for a solution on the internet. Unfortunately, I can find no example (or code) that works without loading and displaying a browser component first. As is the case, with many others out there, I find that I cannot use CoreWebView2?.CookieManager.GetCookiesAsync(url), because the call to EnsureCoreWebView2Async never returns. If anyone can help or has any suggestions that would be greatly appreciated. There must surely be a way to access the cookies without having to have a browser displayed for no reason. Please take a look at the code below and tell me where I am going wrong here. If the answer is "there is no way to access cookies without displaying the WebView2 control first.", please let me know that as well. And please, suggest an alternative for reading the cookies in code only. If needed, I can furnish a complete sample project.

Below is the code that I am using to retrieve the cookies. As previously mentioned

await wv2.EnsureCoreWebView2Async(env);

never returns.

      private async Task GatherCookies(string url = "https://www.google.com")  
        {  
            //corewebview2 environment  
            string appDir = Path.GetDirectoryName((new   
      System.Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath);  
            var profileDir = $@" {Environment.ExpandEnvironmentVariables("temp")}\MyWebView2Profile";  
            var envOpts = new CoreWebView2EnvironmentOptions  
            {  
                AllowSingleSignOnUsingOSPrimaryAccount = true,  
                AdditionalBrowserArguments = $"--log-net-log=   
   {Environment.ExpandEnvironmentVariables($@"{appDir}\{Assembly.GetExecutingAssembly().GetName().Name}_wv2debug.log")}"  
            };  
              
            var env = await CoreWebView2Environment.CreateAsync(null, profileDir, envOpts);  
              
            //webview2 control  
            var wv2 = new Microsoft.Web.WebView2.Wpf.WebView2();  
            wv2.CoreWebView2InitializationCompleted += (s, e) => { Debug.WriteLine($"CoreWebView2 initialization completed"); };  
            await wv2.EnsureCoreWebView2Async(env);  
              
            //access the cookies  
            List<CoreWebView2Cookie> wv2Cookies = new List<CoreWebView2Cookie>();  
            if (wv2.CoreWebView2 != null)  
                wv2Cookies = await wv2.CoreWebView2?.CookieManager.GetCookiesAsync(url);  
            CookieCollection sysNetCookieCollection = new CookieCollection();  
            wv2Cookies.ForEach(c => sysNetCookieCollection.Add(c.ToSystemNetCookie()));  
  
            //set the cookies in the CookieCollection property  
            CookieCollection = sysNetCookieCollection;             
        }   

    private void LoadCookies_Click(object sender, RoutedEventArgs e)  
       {  
            Application.Current.Dispatcher.Invoke(() => GatherCookies());  
       }   

 
     private CookieCollection m_cookieCollection = new CookieCollection();          
     public CookieCollection CookieCollection  
     {  
      get  
        {  
             return m_cookieCollection;  
         }  
    set  
        {  
             m_cookieCollection = value;  
             OnPropertyChanged();  
        }  
     }  
Microsoft Edge
Microsoft Edge
A Microsoft cross-platform web browser that provides privacy, learning, and accessibility tools.
2,114 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
{count} votes

Accepted answer
  1. Castorix31 81,461 Reputation points
    2022-06-25T09:17:06.733+00:00

    MS Edge Cookies are stored in SQLite databases (or in WebCacheV01.dat for the global cache)
    So you can open them, for example with Microsoft.Data.Sqlite
    (from Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +"\Microsoft\Edge\User Data" + ... )
    The database file is Cookies and main table is also cookies
    (you can check the structure with tools like "DB Browser for SQLite")
    (tested on Windows 10 21H1 in C# with .NET Framework 4.8 (e_sqlite3.dll in exe directory for this configuration...))


0 additional answers

Sort by: Most helpful