Accessing cookies in WebView2 using PowerShell

Viewed 674

Using the working example to start a WebView2 instance in PowerShell here: WebView2 in PowerShell Winform GUI

I noticed it maintains cookies nicely between sessions, just like 'normal' Edge. In some scenario's however, manually getting and/or setting cookies could be useful. A specific scenario I'm looking at is using WebView2 session cookies to create a WebDAV connection.

I tried creating a CookieManager like so:

$cookieManager = [Microsoft.Web.WebView2.Core.CoreWebView2CookieManager]

But $cookieManager then doesn't expose any methods to set/get cookies.

1 Answers

You should use the CookieManager property of the CoreWebView2 to obtain the cookie manager for a corresponding CoreWebView2. It will affect all CoreWebView2s that share the same user data folder.

$coreWebView2Initialized = {
    # CookieManager only available after the CoreWebView2 property has been initialized. 
    $cookieManager = $webview.CoreWebView2.CookieManager;
    $cookie = $cookieManager.CreateCookie("name", "value", "example.com", "/");
    $cookieManager.AddOrUpdateCookie($cookie);
}

$webview.add_CoreWebView2InitializationCompleted($coreWebView2Initialized);
Related