Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.BrowserContext.StorageStateAsync
BrowserContext.cs
Source:BrowserContext.cs
...202 public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)203 => Channel.SetExtraHTTPHeadersAsync(headers);204 public Task SetGeolocationAsync(Geolocation geolocation) => Channel.SetGeolocationAsync(geolocation);205 public Task SetOfflineAsync(bool offline) => Channel.SetOfflineAsync(offline);206 public async Task<string> StorageStateAsync(BrowserContextStorageStateOptions options = default)207 {208 string state = JsonSerializer.Serialize(209 await Channel.GetStorageStateAsync().ConfigureAwait(false),210 JsonExtensions.DefaultJsonSerializerOptions);211 if (!string.IsNullOrEmpty(options?.Path))212 {213 File.WriteAllText(options?.Path, state);214 }215 return state;216 }217 public Task UnrouteAsync(string urlString, Action<IRoute> handler = default)218 => UnrouteAsync(new Regex(CombineUrlWithBase(urlString).GlobToRegex()), null, handler);219 public Task UnrouteAsync(Regex urlRegex, Action<IRoute> handler = default)220 => UnrouteAsync(urlRegex, null, handler);221 public Task UnrouteAsync(Func<string, bool> urlFunc, Action<IRoute> handler = default)222 => UnrouteAsync(null, urlFunc, handler);223 public async Task<T> InnerWaitForEventAsync<T>(PlaywrightEvent<T> playwrightEvent, Func<Task> action = default, Func<T, bool> predicate = default, float? timeout = default)...
BrowserContextStorageStateTests.cs
Source:BrowserContextStorageStateTests.cs
...47 await page1.EvaluateAsync(@"() =>48 {49 localStorage['name2'] = 'value2';50 }");51 string storage = await Context.StorageStateAsync();52 // TODO: think about IVT-in the StorageState and serializing53 string expected = @"{""cookies"":[],""origins"":[{""origin"":""https://www.example.com"",""localStorage"":[{""name"":""name1"",""value"":""value1""}]},{""origin"":""https://www.domain.com"",""localStorage"":[{""name"":""name2"",""value"":""value2""}]}]}";54 Assert.AreEqual(expected, storage);55 }56 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should set local storage")]57 public async Task ShouldSetLocalStorage()58 {59 var context = await Browser.NewContextAsync(new()60 {61 StorageState = "{\"cookies\":[],\"origins\":[{\"origin\":\"https://www.example.com\",\"localStorage\":[{\"name\":\"name1\",\"value\":\"value1\"}]}]}",62 });63 var page = await context.NewPageAsync();64 await page.RouteAsync("**/*", (route) =>65 {66 route.FulfillAsync(new() { Body = "<html></html>" });67 });68 await page.GotoAsync("https://www.example.com");69 var localStorage = await page.EvaluateAsync<string[]>("Object.keys(window.localStorage)");70 Assert.AreEqual(localStorage, new string[] { "name1" });71 var name1Value = await page.EvaluateAsync<string>("window.localStorage.getItem('name1')");72 Assert.AreEqual(name1Value, "value1");73 }74 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should round-trip through the file")]75 public async Task ShouldRoundTripThroughTheFile()76 {77 var page1 = await Context.NewPageAsync();78 await page1.RouteAsync("**/*", (route) =>79 {80 route.FulfillAsync(new() { Body = "<html></html>" });81 });82 await page1.GotoAsync("https://www.example.com");83 await page1.EvaluateAsync(@"() =>84 {85 localStorage['name1'] = 'value1';86 document.cookie = 'username=John Doe';87 }");88 using var tempDir = new TempDirectory();89 string path = Path.Combine(tempDir.Path, "storage-state.json");90 string storage = await Context.StorageStateAsync(new() { Path = path });91 Assert.AreEqual(storage, File.ReadAllText(path));92 await using var context = await Browser.NewContextAsync(new() { StorageStatePath = path });93 var page2 = await context.NewPageAsync();94 await page2.RouteAsync("**/*", (route) =>95 {96 route.FulfillAsync(new() { Body = "<html></html>" });97 });98 await page2.GotoAsync("https://www.example.com");99 Assert.AreEqual("value1", await page2.EvaluateAsync<string>("localStorage['name1']"));100 Assert.AreEqual("username=John Doe", await page2.EvaluateAsync<string>("document.cookie"));101 }102 [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture cookies")]103 public async Task ShouldCaptureCookies()104 {105 Server.SetRoute("/setcookie.html", context =>106 {107 context.Response.Cookies.Append("a", "b");108 context.Response.Cookies.Append("empty", "");109 return Task.CompletedTask;110 });111 await Page.GotoAsync(Server.Prefix + "/setcookie.html");112 CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await Page.EvaluateAsync<string[]>(@"() =>113 {114 const cookies = document.cookie.split(';');115 return cookies.map(cookie => cookie.trim()).sort();116 }"));117 var storageState = await Context.StorageStateAsync();118 StringAssert.Contains(@"""name"":""a"",""value"":""b""", storageState);119 StringAssert.Contains(@"""name"":""empty"",""value"":""""", storageState);120 if (TestConstants.IsWebKit || TestConstants.IsFirefox)121 {122 StringAssert.Contains(@"""sameSite"":""None""", storageState);123 }124 else125 {126 StringAssert.Contains(@"""sameSite"":""Lax""", storageState);127 }128 StringAssert.DoesNotContain(@"""url"":null", storageState);129 await using var context2 = await Browser.NewContextAsync(new() { StorageState = storageState });130 var page2 = await context2.NewPageAsync();131 await page2.GotoAsync(Server.EmptyPage);...
StorageStateAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 await page.FillAsync("input[name=q]", "Playwright");15 await page.PressAsync("input[name=q]", "Enter");16 await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);17 await context.StorageStateAsync(new BrowserContextStorageStateOptions18 {19 });20 }21 }22}23using System;24using System.Threading.Tasks;25using Microsoft.Playwright;26{27 {28 static async Task Main(string[] args)29 {30 using var playwright = await Playwright.CreateAsync();31 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions32 {33 });34 var context = await browser.NewContextAsync(new Browser.NewContextOptions35 {36 });37 var page = await context.NewPageAsync();38 await page.FillAsync("input[name=q]", "Playwright");39 await page.PressAsync("input[name=q]", "Enter");40 await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);41 }42 }43}44using System;45using System.Threading.Tasks;46using Microsoft.Playwright;47{48 {49 static async Task Main(string[] args)50 {51 using var playwright = await Playwright.CreateAsync();52 await using var browser = await playwright.Chromium.LaunchAsync(new
StorageStateAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var context = await browser.NewContextAsync();11 var page = await context.NewPageAsync();12 await context.StorageStateAsync(path: "C:\\Users\\Nik\\Desktop\\storage.json");13 await context.CloseAsync();14 }15 }16}17using Microsoft.Playwright;18using System;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 using var playwright = await Playwright.CreateAsync();25 await using var browser = await playwright.Chromium.LaunchAsync();26 var context = await browser.NewContextAsync();27 var page = await context.NewPageAsync();28 await context.StorageStateAsync(path: "C:\\Users\\Nik\\Desktop\\storage.json");29 await context.CloseAsync();30 await using var browser1 = await playwright.Chromium.LaunchAsync();31 var context1 = await browser1.NewContextAsync(storageStatePath: "C:\\Users\\Nik\\Desktop\\storage.json");32 var page1 = await context1.NewPageAsync();33 }34 }35}
StorageStateAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 var playwright = await Playwright.CreateAsync();8 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions9 {10 });11 var context = await browser.NewContextAsync(new BrowserNewContextOptions12 {13 {14 {15 {16 },17 {18 },19 },20 {21 {22 {23 {24 },25 {26 },27 },28 },29 },30 },31 });32 var page = await context.NewPageAsync();33 await page.ScreenshotAsync("screenshot.png");34 await browser.CloseAsync();35 }36 }37}38using Microsoft.Playwright;39using System;40using System.Collections.Generic;41using System.Threading.Tasks;42{43 {44 static async Task Main(string[] args)45 {46 var playwright = await Playwright.CreateAsync();47 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions48 {49 });50 var context = await browser.NewContextAsync(new BrowserNewContextOptions51 {52 {53 {54 {
StorageStateAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Collections.Generic;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 await using var playwright = await Microsoft.Playwright.Core.Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var context = await browser.NewContextAsync(new BrowserNewContextOptions14 {15 });16 var page = await context.NewPageAsync();17 Console.ReadLine();18 }19 }20}
StorageStateAsync
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 var state = await context.StorageStateAsync();15 Console.WriteLine(state);16 await browser.CloseAsync();17 }18 }19}20{ "cookies": [], "origins": [] }
StorageStateAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });10 var context = await browser.NewContextAsync(new BrowserNewContextOptions11 {12 {13 Size = new BrowserNewContextOptionsVideoSizeSize { Width = 1920, Height = 1080 }14 }15 });16 var page = await context.NewPageAsync();17 await page.TypeAsync("input[name=q]", "Hello World");18 await page.PressAsync("input[name=q]", "Enter");19 await Task.Delay(5000);20 await page.ScreenshotAsync("C:\\Users\\user\\Desktop\\screenshot.png");21 await context.CloseAsync();22 }23 }24}
StorageStateAsync
Using AI Code Generation
1using System.Threading.Tasks;2using Microsoft.Playwright;3{4 {5 private static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync();9 var context = await browser.NewContextAsync();10 var page = await context.NewPageAsync();11 await context.StorageStateAsync(path: "2.json");12 await page.CloseAsync();13 await context.CloseAsync();
StorageStateAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var context = await browser.NewContextAsync(new BrowserNewContextOptions14 {15 });16 var page = await context.NewPageAsync();17 await page.ScreenshotAsync("google.png");18 await context.StorageStateAsync(new { path = "storage.json" });19 await browser.CloseAsync();20 }21 }22}23using System;24using System.Threading.Tasks;25using Microsoft.Playwright;26{27 {28 static async Task Main(string[] args)29 {30 Console.WriteLine("Hello World!");31 using var playwright = await Playwright.CreateAsync();32 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions33 {34 });35 var context = await browser.NewContextAsync(new BrowserNewContextOptions36 {37 });38 var page = await context.NewPageAsync();39 await page.ScreenshotAsync("google.png");40 await context.StorageStateAsync(new { path = "storage.json" });41 await browser.CloseAsync();42 }43 }
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!