TsgcWebView2 exposes a CookieManager property for reading, creating, updating, and deleting cookies in the browser context.
Use CookieManager.GetCookies to retrieve cookies for a given URI. The method returns a list of cookie objects that you can iterate.
procedure TFormMain.ButtonGetCookiesClick(Sender: TObject);
var
vCookies: TsgcWebView2CookieList;
i: Integer;
begin
vCookies := sgcWebView21.CookieManager.GetCookies(
'https://www.example.com');
try
for i := 0 to vCookies.Count - 1 do
Memo1.Lines.Add(
vCookies[i].Name + ' = ' + vCookies[i].Value);
finally
vCookies.Free;
end;
end;
Use CookieManager.AddOrUpdateCookie to create a new cookie or update an existing one. Specify the name, value, domain, and path at minimum.
// Add a session cookie
sgcWebView21.CookieManager.AddOrUpdateCookie(
'session_id', // name
'abc123def456', // value
'.example.com', // domain
'/'); // path
// Add a cookie with an expiration date
sgcWebView21.CookieManager.AddOrUpdateCookie(
'preferences', // name
'theme=dark', // value
'.example.com', // domain
'/', // path
Now + 30); // expires in 30 days
Use DeleteCookie to remove a specific cookie by name and URI. Use DeleteAllCookies to clear all cookies from the browser.
// Delete a specific cookie
sgcWebView21.CookieManager.DeleteCookie(
'session_id',
'https://www.example.com');
// Delete cookies matching a domain and path
sgcWebView21.CookieManager.DeleteCookiesWithDomainAndPath(
'session_id',
'.example.com',
'/');
// Delete all cookies
sgcWebView21.CookieManager.DeleteAllCookies;