How to use StorageState class of Microsoft.Playwright.Core package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.StorageState

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

BrowserContextStorageStateTests.cs

Source: BrowserContextStorageStateTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System.IO;
26using System.Text.Json;
27using System.Threading.Tasks;
28using Microsoft.Playwright.Core;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    public sealed class BrowsercontextStorageStateTests : PageTestEx
34    {
35        [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture local storage")]
36        public async Task ShouldCaptureLocalStorage()
37        {
38            var page1 = await Context.NewPageAsync();
39            await page1.RouteAsync("**/*", (route) =>
40            {
41                route.FulfillAsync(new() { Body = "<html></html>" });
42            });
43
44            await page1.GotoAsync("https://www.example.com");
45            await page1.EvaluateAsync(@"() =>
46            {
47                localStorage['name1'] = 'value1';
48            }");
49            await page1.GotoAsync("https://www.domain.com");
50            await page1.EvaluateAsync(@"() =>
51            {
52                localStorage['name2'] = 'value2';
53            }");
54
55            string storage = await Context.StorageStateAsync();
56
57            // TODO: think about IVT-in the StorageState and serializing
58            string expected = @"{""cookies"":[],""origins"":[{""origin"":""https://www.example.com"",""localStorage"":[{""name"":""name1"",""value"":""value1""}]},{""origin"":""https://www.domain.com"",""localStorage"":[{""name"":""name2"",""value"":""value2""}]}]}";
59            Assert.AreEqual(expected, storage);
60        }
61
62        [PlaywrightTest("browsercontext-storage-state.spec.ts", "should set local storage")]
63        public async Task ShouldSetLocalStorage()
64        {
65            var context = await Browser.NewContextAsync(new()
66            {
67                StorageState = "{\"cookies\":[],\"origins\":[{\"origin\":\"https://www.example.com\",\"localStorage\":[{\"name\":\"name1\",\"value\":\"value1\"}]}]}",
68            });
69            var page = await context.NewPageAsync();
70            await page.RouteAsync("**/*", (route) =>
71            {
72                route.FulfillAsync(new() { Body = "<html></html>" });
73            });
74            await page.GotoAsync("https://www.example.com");
75            var localStorage = await page.EvaluateAsync<string[]>("Object.keys(window.localStorage)");
76            Assert.AreEqual(localStorage, new string[] { "name1" });
77            var name1Value = await page.EvaluateAsync<string>("window.localStorage.getItem('name1')");
78            Assert.AreEqual(name1Value, "value1");
79        }
80
81        [PlaywrightTest("browsercontext-storage-state.spec.ts", "should round-trip through the file")]
82        public async Task ShouldRoundTripThroughTheFile()
83        {
84            var page1 = await Context.NewPageAsync();
85            await page1.RouteAsync("**/*", (route) =>
86            {
87                route.FulfillAsync(new() { Body = "<html></html>" });
88            });
89
90            await page1.GotoAsync("https://www.example.com");
91            await page1.EvaluateAsync(@"() =>
92            {
93                localStorage['name1'] = 'value1';
94                document.cookie = 'username=John Doe';
95            }");
96            using var tempDir = new TempDirectory();
97            string path = Path.Combine(tempDir.Path, "storage-state.json");
98            string storage = await Context.StorageStateAsync(new() { Path = path });
99            Assert.AreEqual(storage, File.ReadAllText(path));
100
101            await using var context = await Browser.NewContextAsync(new() { StorageStatePath = path });
102            var page2 = await context.NewPageAsync();
103            await page2.RouteAsync("**/*", (route) =>
104            {
105                route.FulfillAsync(new() { Body = "<html></html>" });
106            });
107
108            await page2.GotoAsync("https://www.example.com");
109            Assert.AreEqual("value1", await page2.EvaluateAsync<string>("localStorage['name1']"));
110            Assert.AreEqual("username=John Doe", await page2.EvaluateAsync<string>("document.cookie"));
111        }
112
113        [PlaywrightTest("browsercontext-storage-state.spec.ts", "should capture cookies")]
114        public async Task ShouldCaptureCookies()
115        {
116            Server.SetRoute("/setcookie.html", context =>
117            {
118                context.Response.Cookies.Append("a", "b");
119                context.Response.Cookies.Append("empty", "");
120                return Task.CompletedTask;
121            });
122
123            await Page.GotoAsync(Server.Prefix + "/setcookie.html");
124            CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await Page.EvaluateAsync<string[]>(@"() =>
125            {
126                const cookies = document.cookie.split(';');
127                return cookies.map(cookie => cookie.trim()).sort();
128            }"));
129
130            var storageState = await Context.StorageStateAsync();
131            StringAssert.Contains(@"""name"":""a"",""value"":""b""", storageState);
132            StringAssert.Contains(@"""name"":""empty"",""value"":""""", storageState);
133            if (TestConstants.IsWebKit || TestConstants.IsFirefox)
134            {
135                StringAssert.Contains(@"""sameSite"":""None""", storageState);
136            }
137            else
138            {
139                StringAssert.Contains(@"""sameSite"":""Lax""", storageState);
140            }
141            StringAssert.DoesNotContain(@"""url"":null", storageState);
142
143            await using var context2 = await Browser.NewContextAsync(new() { StorageState = storageState });
144            var page2 = await context2.NewPageAsync();
145            await page2.GotoAsync(Server.EmptyPage);
146            CollectionAssert.AreEqual(new[] { "a=b", "empty=" }, await page2.EvaluateAsync<string[]>(@"() =>
147            {
148                const cookies = document.cookie.split(';');
149                return cookies.map(cookie => cookie.trim()).sort();
150            }"));
151        }
152    }
153}
154
Full Screen

BrowserChannel.cs

Source: BrowserChannel.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.IO;
28using System.Linq;
29using System.Text.Json;
30using System.Threading.Tasks;
31using Microsoft.Playwright.Core;
32using Microsoft.Playwright.Transport.Protocol;
33
34namespace Microsoft.Playwright.Transport.Channels
35{
36    internal class BrowserChannel : Channel<Browser>
37    {
38        public BrowserChannel(string guid, Connection connection, Browser owner) : base(guid, connection, owner)
39        {
40        }
41
42        internal event EventHandler Closed;
43
44        internal override void OnMessage(string method, JsonElement? serverParams)
45        {
46            switch (method)
47            {
48                case "close":
49                    Closed?.Invoke(this, EventArgs.Empty);
50                    break;
51            }
52        }
53
54        internal Task<BrowserContextChannel> NewContextAsync(
55            bool? acceptDownloads = null,
56            bool? bypassCSP = null,
57            ColorScheme? colorScheme = null,
58            ReducedMotion? reducedMotion = null,
59            ForcedColors? forcedColors = null,
60            float? deviceScaleFactor = null,
61            IEnumerable<KeyValuePair<string, string>> extraHTTPHeaders = null,
62            Geolocation geolocation = null,
63            bool? hasTouch = null,
64            HttpCredentials httpCredentials = null,
65            bool? ignoreHTTPSErrors = null,
66            bool? isMobile = null,
67            bool? javaScriptEnabled = null,
68            string locale = null,
69            bool? offline = null,
70            IEnumerable<string> permissions = null,
71            Proxy proxy = null,
72            bool? recordHarOmitContent = null,
73            string recordHarPath = null,
74            Dictionary<string, object> recordVideo = null,
75            string storageState = null,
76            string storageStatePath = null,
77            string timezoneId = null,
78            string userAgent = null,
79            ViewportSize viewportSize = default,
80            ScreenSize screenSize = default,
81            string baseUrl = default,
82            bool? strictSelectors = default)
83        {
84            var args = new Dictionary<string, object>
85            {
86                { "acceptDownloads", acceptDownloads },
87                { "bypassCSP", bypassCSP },
88                { "colorScheme", colorScheme },
89                { "reducedMotion", reducedMotion },
90                { "deviceScaleFactor", deviceScaleFactor },
91            };
92
93            if (extraHTTPHeaders != null)
94            {
95                args["extraHTTPHeaders"] = extraHTTPHeaders.Select(kv => new HeaderEntry { Name = kv.Key, Value = kv.Value }).ToArray();
96            }
97
98            args.Add("geolocation", geolocation);
99            args.Add("hasTouch", hasTouch);
100            args.Add("httpCredentials", httpCredentials);
101            args.Add("ignoreHTTPSErrors", ignoreHTTPSErrors);
102            args.Add("isMobile", isMobile);
103            args.Add("javaScriptEnabled", javaScriptEnabled);
104            args.Add("locale", locale);
105            args.Add("offline", offline);
106            args.Add("permissions", permissions);
107            args.Add("proxy", proxy);
108            args.Add("strictSelectors", strictSelectors);
109            args.Add("forcedColors", forcedColors);
110
111            if (!string.IsNullOrEmpty(recordHarPath))
112            {
113                args.Add("recordHar", new
114                {
115                    Path = recordHarPath,
116                    OmitContent = recordHarOmitContent,
117                });
118            }
119
120            if (recordVideo != null)
121            {
122                args.Add("recordVideo", recordVideo);
123            }
124
125            if (!string.IsNullOrEmpty(storageStatePath))
126            {
127                if (!File.Exists(storageStatePath))
128                {
129                    throw new PlaywrightException($"The specified storage state file does not exist: {storageStatePath}");
130                }
131
132                storageState = File.ReadAllText(storageStatePath);
133            }
134
135            if (!string.IsNullOrEmpty(storageState))
136            {
137                args.Add("storageState", JsonSerializer.Deserialize<StorageState>(storageState, Helpers.JsonExtensions.DefaultJsonSerializerOptions));
138            }
139
140            args.Add("timezoneId", timezoneId);
141            args.Add("userAgent", userAgent);
142
143            if (viewportSize?.Width == -1)
144            {
145                args.Add("noDefaultViewport", true);
146            }
147            else
148            {
149                args.Add("viewport", viewportSize);
150                args.Add("screen", screenSize);
151            }
152
153            args.Add("baseURL", baseUrl);
154
155            return Connection.SendMessageToServerAsync<BrowserContextChannel>(
156                Guid,
157                "newContext",
158                args);
159        }
160
161        internal Task CloseAsync() => Connection.SendMessageToServerAsync<BrowserContextChannel>(Guid, "close", null);
162
163        internal Task StartTracingAsync(IPage page, bool screenshots, string path, IEnumerable<string> categories)
164        {
165            var args = new Dictionary<string, object>
166            {
167                ["screenshots"] = screenshots,
168                ["path"] = path,
169                ["page"] = page,
170                ["categories"] = categories,
171            };
172
173            return Connection.SendMessageToServerAsync(Guid, "crStartTracing", args);
174        }
175
176        internal async Task<string> StopTracingAsync()
177            => (await Connection.SendMessageToServerAsync(Guid, "crStopTracing", null).ConfigureAwait(false))?.GetProperty("binary").ToString();
178    }
179}
180
Full Screen

Browser.cs

Source: Browser.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.Threading.Tasks;
28using Microsoft.Playwright.Transport;
29using Microsoft.Playwright.Transport.Channels;
30using Microsoft.Playwright.Transport.Protocol;
31
32namespace Microsoft.Playwright.Core
33{
34    internal class Browser : ChannelOwnerBase, IChannelOwner<Browser>, IBrowser
35    {
36        private readonly BrowserInitializer _initializer;
37        private readonly TaskCompletionSource<bool> _closedTcs = new();
38
39        internal Browser(IChannelOwner parent, string guid, BrowserInitializer initializer) : base(parent, guid)
40        {
41            Channel = new(guid, parent.Connection, this);
42            IsConnected = true;
43            Channel.Closed += (_, _) => DidClose();
44            _initializer = initializer;
45        }
46
47        public event EventHandler<IBrowser> Disconnected;
48
49        ChannelBase IChannelOwner.Channel => Channel;
50
51        IChannel<Browser> IChannelOwner<Browser>.Channel => Channel;
52
53        public IReadOnlyList<IBrowserContext> Contexts => BrowserContextsList.ToArray();
54
55        public bool IsConnected { get; private set; }
56
57        internal bool ShouldCloseConnectionOnClose { get; set; }
58
59        public string Version => _initializer.Version;
60
61        internal BrowserChannel Channel { get; }
62
63        internal List<BrowserContext> BrowserContextsList { get; } = new();
64
65        internal LocalUtils LocalUtils { get; set; }
66
67        public async Task CloseAsync()
68        {
69            try
70            {
71                if (ShouldCloseConnectionOnClose)
72                {
73                    Channel.Connection.DoClose(DriverMessages.BrowserClosedExceptionMessage);
74                }
75                else
76                {
77                    await Channel.CloseAsync().ConfigureAwait(false);
78                }
79                await _closedTcs.Task.ConfigureAwait(false);
80            }
81            catch (Exception e) when (DriverMessages.IsSafeCloseError(e))
82            {
83                // Swallow exception
84            }
85        }
86
87        public async Task<IBrowserContext> NewContextAsync(BrowserNewContextOptions options = default)
88        {
89            options ??= new();
90            var context = (await Channel.NewContextAsync(
91               acceptDownloads: options.AcceptDownloads,
92               bypassCSP: options.BypassCSP,
93               colorScheme: options.ColorScheme,
94               reducedMotion: options.ReducedMotion,
95               deviceScaleFactor: options.DeviceScaleFactor,
96               extraHTTPHeaders: options.ExtraHTTPHeaders,
97               geolocation: options.Geolocation,
98               hasTouch: options.HasTouch,
99               httpCredentials: options.HttpCredentials,
100               ignoreHTTPSErrors: options.IgnoreHTTPSErrors,
101               isMobile: options.IsMobile,
102               javaScriptEnabled: options.JavaScriptEnabled,
103               locale: options.Locale,
104               offline: options.Offline,
105               permissions: options.Permissions,
106               proxy: options.Proxy,
107               recordHarOmitContent: options.RecordHarOmitContent,
108               recordHarPath: options.RecordHarPath,
109               recordVideo: GetVideoArgs(options.RecordVideoDir, options.RecordVideoSize),
110               storageState: options.StorageState,
111               storageStatePath: options.StorageStatePath,
112               timezoneId: options.TimezoneId,
113               userAgent: options.UserAgent,
114               viewportSize: options.ViewportSize,
115               screenSize: options.ScreenSize,
116               baseUrl: options.BaseURL,
117               strictSelectors: options.StrictSelectors,
118               forcedColors: options.ForcedColors).ConfigureAwait(false)).Object;
119
120            context.Options = options;
121            ((Tracing)context.Tracing).LocalUtils = LocalUtils;
122
123            BrowserContextsList.Add(context);
124            return context;
125        }
126
127        public async Task<IPage> NewPageAsync(BrowserNewPageOptions options = default)
128        {
129            options ??= new();
130
131            var contextOptions = new BrowserNewContextOptions()
132            {
133                AcceptDownloads = options.AcceptDownloads,
134                IgnoreHTTPSErrors = options.IgnoreHTTPSErrors,
135                BypassCSP = options.BypassCSP,
136                ViewportSize = options.ViewportSize,
137                ScreenSize = options.ScreenSize,
138                UserAgent = options.UserAgent,
139                DeviceScaleFactor = options.DeviceScaleFactor,
140                IsMobile = options.IsMobile,
141                HasTouch = options.HasTouch,
142                JavaScriptEnabled = options.JavaScriptEnabled,
143                TimezoneId = options.TimezoneId,
144                Geolocation = options.Geolocation,
145                Locale = options.Locale,
146                Permissions = options.Permissions,
147                ExtraHTTPHeaders = options.ExtraHTTPHeaders,
148                Offline = options.Offline,
149                HttpCredentials = options.HttpCredentials,
150                ColorScheme = options.ColorScheme,
151                ReducedMotion = options.ReducedMotion,
152                ForcedColors = options.ForcedColors,
153                RecordHarPath = options.RecordHarPath,
154                RecordHarOmitContent = options.RecordHarOmitContent,
155                RecordVideoDir = options.RecordVideoDir,
156                RecordVideoSize = options.RecordVideoSize,
157                Proxy = options.Proxy,
158                StorageState = options.StorageState,
159                StorageStatePath = options.StorageStatePath,
160                BaseURL = options.BaseURL,
161                StrictSelectors = options.StrictSelectors,
162            };
163
164            var context = (BrowserContext)await NewContextAsync(contextOptions).ConfigureAwait(false);
165
166            var page = (Page)await context.NewPageAsync().ConfigureAwait(false);
167            page.OwnedContext = context;
168            context.Options = contextOptions;
169            context.OwnerPage = page;
170            return page;
171        }
172
173        public ValueTask DisposeAsync() => new ValueTask(CloseAsync());
174
175        internal static Dictionary<string, object> GetVideoArgs(string recordVideoDir, RecordVideoSize recordVideoSize)
176        {
177            Dictionary<string, object> recordVideoArgs = null;
178
179            if (recordVideoSize != null && string.IsNullOrEmpty(recordVideoDir))
180            {
181                throw new PlaywrightException("\"RecordVideoSize\" option requires \"RecordVideoDir\" to be specified");
182            }
183
184            if (!string.IsNullOrEmpty(recordVideoDir))
185            {
186                recordVideoArgs = new()
187                {
188                    { "dir", recordVideoDir },
189                };
190
191                if (recordVideoSize != null)
192                {
193                    recordVideoArgs["size"] = recordVideoSize;
194                }
195            }
196
197            return recordVideoArgs;
198        }
199
200        internal void DidClose()
201        {
202            IsConnected = false;
203            Disconnected?.Invoke(this, this);
204            _closedTcs.TrySetResult(true);
205        }
206    }
207}
208
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in StorageState

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)