How to use RouteChannel class of Microsoft.Playwright.Transport.Channels package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Transport.Channels.RouteChannel

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

RouteChannel.cs

Source: RouteChannel.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.Linq;
28using System.Threading.Tasks;
29using Microsoft.Playwright.Core;
30using Microsoft.Playwright.Transport.Protocol;
31
32namespace Microsoft.Playwright.Transport.Channels
33{
34    internal class RouteChannel : Channel<Route>
35    {
36        public RouteChannel(string guid, Connection connection, Route owner) : base(guid, connection, owner)
37        {
38        }
39
40        public Task AbortAsync(string errorCode)
41            => Connection.SendMessageToServerAsync(
42                Guid,
43                "abort",
44                new Dictionary<string, object>
45                {
46                    ["errorCode"] = string.IsNullOrEmpty(errorCode) ? RequestAbortErrorCode.Failed : errorCode,
47                });
48
49        public Task FulfillAsync(NormalizedFulfillResponse response)
50            => Connection.SendMessageToServerAsync(
51                Guid,
52                "fulfill",
53                response);
54
55        public Task ContinueAsync(string url, string method, byte[] postData, IEnumerable<KeyValuePair<string, string>> headers)
56        {
57            var args = new Dictionary<string, object>
58            {
59                ["url"] = url,
60                ["method"] = method,
61            };
62            if (postData != null)
63            {
64                args["postData"] = Convert.ToBase64String(postData);
65            }
66
67            if (headers != null)
68            {
69                args["headers"] = headers.Select(kv => new HeaderEntry { Name = kv.Key, Value = kv.Value }).ToArray();
70            }
71
72            return Connection.SendMessageToServerAsync(
73                Guid,
74                "continue",
75                args);
76        }
77    }
78}
79
Full Screen

Route.cs

Source: Route.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.Net;
30using System.Threading.Tasks;
31using Microsoft.Playwright.Helpers;
32using Microsoft.Playwright.Transport;
33using Microsoft.Playwright.Transport.Channels;
34using Microsoft.Playwright.Transport.Protocol;
35
36namespace Microsoft.Playwright.Core
37{
38    /// <summary>
39    /// <see cref="IRoute"/>.
40    /// </summary>
41    internal partial class Route : ChannelOwnerBase, IChannelOwner<Route>, IRoute
42    {
43        private readonly RouteChannel _channel;
44        private readonly RouteInitializer _initializer;
45
46        internal Route(IChannelOwner parent, string guid, RouteInitializer initializer) : base(parent, guid)
47        {
48            _channel = new(guid, parent.Connection, this);
49            _initializer = initializer;
50        }
51
52        /// <summary>
53        /// A request to be routed.
54        /// </summary>
55        public IRequest Request => _initializer.Request;
56
57        ChannelBase IChannelOwner.Channel => _channel;
58
59        IChannel<Route> IChannelOwner<Route>.Channel => _channel;
60
61        public Task FulfillAsync(RouteFulfillOptions options = default)
62        {
63            options ??= new RouteFulfillOptions();
64            var normalized = NormalizeFulfillParameters(
65                options.Status,
66                options.Headers,
67                options.ContentType,
68                options.Body,
69                options.BodyBytes,
70                options.Path);
71
72            return RaceWithPageCloseAsync(_channel.FulfillAsync(normalized));
73        }
74
75        public Task AbortAsync(string errorCode = RequestAbortErrorCode.Failed) => RaceWithPageCloseAsync(_channel.AbortAsync(errorCode));
76
77        public Task ContinueAsync(RouteContinueOptions options = default)
78        {
79            options ??= new RouteContinueOptions();
80            return RaceWithPageCloseAsync(_channel.ContinueAsync(url: options.Url, method: options.Method, postData: options.PostData, headers: options.Headers));
81        }
82
83        private async Task RaceWithPageCloseAsync(Task task)
84        {
85            var page = (Page)Request.Frame.Page;
86            if (page == null)
87            {
88                task.IgnoreException();
89                return;
90            }
91
92            // When page closes or crashes, we catch any potential rejects from this Route.
93            // Note that page could be missing when routing popup's initial request that
94            // does not have a Page initialized just yet.
95            if (task != await Task.WhenAny(task, page.ClosedOrCrashedTcs.Task).ConfigureAwait(false))
96            {
97                task.IgnoreException();
98            }
99            else
100            {
101                await task.ConfigureAwait(false);
102            }
103        }
104
105        private NormalizedFulfillResponse NormalizeFulfillParameters(
106            int? status,
107            IEnumerable<KeyValuePair<string, string>> headers,
108            string contentType,
109            string body,
110            byte[] bodyContent,
111            string path)
112        {
113            string resultBody = string.Empty;
114            bool isBase64 = false;
115            int length = 0;
116
117            if (!string.IsNullOrEmpty(path))
118            {
119                byte[] content = File.ReadAllBytes(path);
120                resultBody = Convert.ToBase64String(content);
121                isBase64 = true;
122                length = resultBody.Length;
123            }
124            else if (!string.IsNullOrEmpty(body))
125            {
126                resultBody = body;
127                isBase64 = false;
128                length = resultBody.Length;
129            }
130            else if (bodyContent != null)
131            {
132                resultBody = Convert.ToBase64String(bodyContent);
133                isBase64 = true;
134                length = resultBody.Length;
135            }
136
137            var resultHeaders = new Dictionary<string, string>();
138
139            if (headers != null)
140            {
141                foreach (var header in headers)
142                {
143                    resultHeaders[header.Key.ToLower()] = header.Value;
144                }
145            }
146
147            if (!string.IsNullOrEmpty(contentType))
148            {
149                resultHeaders["content-type"] = contentType;
150            }
151            else if (!string.IsNullOrEmpty(path))
152            {
153                resultHeaders["content-type"] = path.GetContentType();
154            }
155
156            if (length > 0 && !resultHeaders.ContainsKey("content-length"))
157            {
158                resultHeaders["content-length"] = length.ToString();
159            }
160
161            return new()
162            {
163                Status = status ?? (int)HttpStatusCode.OK,
164                Headers = resultHeaders.Select(kv => new HeaderEntry { Name = kv.Key, Value = kv.Value }).ToArray(),
165                Body = resultBody,
166                IsBase64 = isBase64,
167            };
168        }
169    }
170}
171
Full Screen

BrowserContextChannel.cs

Source: BrowserContextChannel.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.Linq;
28using System.Text.Json;
29using System.Threading.Tasks;
30using Microsoft.Playwright.Core;
31using Microsoft.Playwright.Helpers;
32using Microsoft.Playwright.Transport.Protocol;
33
34namespace Microsoft.Playwright.Transport.Channels
35{
36    internal class BrowserContextChannel : Channel<BrowserContext>
37    {
38        public BrowserContextChannel(string guid, Connection connection, BrowserContext owner) : base(guid, connection, owner)
39        {
40        }
41
42        internal event EventHandler Close;
43
44        internal event EventHandler<BrowserContextPageEventArgs> Page;
45
46        internal event EventHandler<BrowserContextPageEventArgs> BackgroundPage;
47
48        internal event EventHandler<WorkerChannelEventArgs> ServiceWorker;
49
50        internal event EventHandler<BindingCallEventArgs> BindingCall;
51
52        internal event EventHandler<RouteEventArgs> Route;
53
54        internal event EventHandler<BrowserContextChannelRequestEventArgs> Request;
55
56        internal event EventHandler<BrowserContextChannelRequestEventArgs> RequestFinished;
57
58        internal event EventHandler<BrowserContextChannelRequestEventArgs> RequestFailed;
59
60        internal event EventHandler<BrowserContextChannelResponseEventArgs> Response;
61
62        internal override void OnMessage(string method, JsonElement? serverParams)
63        {
64            switch (method)
65            {
66                case "close":
67                    Close?.Invoke(this, EventArgs.Empty);
68                    break;
69                case "bindingCall":
70                    BindingCall?.Invoke(
71                        this,
72                        new() { BindingCall = serverParams?.GetProperty("binding").ToObject<BindingCallChannel>(Connection.DefaultJsonSerializerOptions).Object });
73                    break;
74                case "route":
75                    var route = serverParams?.GetProperty("route").ToObject<RouteChannel>(Connection.DefaultJsonSerializerOptions).Object;
76                    var request = serverParams?.GetProperty("request").ToObject<RequestChannel>(Connection.DefaultJsonSerializerOptions).Object;
77                    Route?.Invoke(
78                        this,
79                        new() { Route = route, Request = request });
80                    break;
81                case "page":
82                    Page?.Invoke(
83                        this,
84                        new() { PageChannel = serverParams?.GetProperty("page").ToObject<PageChannel>(Connection.DefaultJsonSerializerOptions) });
85                    break;
86                case "crBackgroundPage":
87                    BackgroundPage?.Invoke(
88                        this,
89                        new() { PageChannel = serverParams?.GetProperty("page").ToObject<PageChannel>(Connection.DefaultJsonSerializerOptions) });
90                    break;
91                case "crServiceWorker":
92                    ServiceWorker?.Invoke(
93                        this,
94                        new() { WorkerChannel = serverParams?.GetProperty("worker").ToObject<WorkerChannel>(Connection.DefaultJsonSerializerOptions) });
95                    break;
96                case "request":
97                    Request?.Invoke(this, serverParams?.ToObject<BrowserContextChannelRequestEventArgs>(Connection.DefaultJsonSerializerOptions));
98                    break;
99                case "requestFinished":
100                    RequestFinished?.Invoke(this, serverParams?.ToObject<BrowserContextChannelRequestEventArgs>(Connection.DefaultJsonSerializerOptions));
101                    break;
102                case "requestFailed":
103                    RequestFailed?.Invoke(this, serverParams?.ToObject<BrowserContextChannelRequestEventArgs>(Connection.DefaultJsonSerializerOptions));
104                    break;
105                case "response":
106                    Response?.Invoke(this, serverParams?.ToObject<BrowserContextChannelResponseEventArgs>(Connection.DefaultJsonSerializerOptions));
107                    break;
108            }
109        }
110
111        internal Task<PageChannel> NewPageAsync()
112            => Connection.SendMessageToServerAsync<PageChannel>(
113                Guid,
114                "newPage",
115                null);
116
117        internal Task CloseAsync() => Connection.SendMessageToServerAsync(Guid, "close");
118
119        internal Task PauseAsync()
120            => Connection.SendMessageToServerAsync(Guid, "pause", null);
121
122        internal Task SetDefaultNavigationTimeoutNoReplyAsync(float timeout)
123            => Connection.SendMessageToServerAsync<PageChannel>(
124                Guid,
125                "setDefaultNavigationTimeoutNoReply",
126                new Dictionary<string, object>
127                {
128                    ["timeout"] = timeout,
129                });
130
131        internal Task SetDefaultTimeoutNoReplyAsync(float timeout)
132            => Connection.SendMessageToServerAsync<PageChannel>(
133                Guid,
134                "setDefaultTimeoutNoReply",
135                new Dictionary<string, object>
136                {
137                    ["timeout"] = timeout,
138                });
139
140        internal Task ExposeBindingAsync(string name, bool needsHandle)
141            => Connection.SendMessageToServerAsync<PageChannel>(
142                Guid,
143                "exposeBinding",
144                new Dictionary<string, object>
145                {
146                    ["name"] = name,
147                    ["needsHandle"] = needsHandle,
148                });
149
150        internal Task AddInitScriptAsync(string script)
151            => Connection.SendMessageToServerAsync<PageChannel>(
152                Guid,
153                "addInitScript",
154                new Dictionary<string, object>
155                {
156                    ["source"] = script,
157                });
158
159        internal Task SetNetworkInterceptionEnabledAsync(bool enabled)
160            => Connection.SendMessageToServerAsync<PageChannel>(
161                Guid,
162                "setNetworkInterceptionEnabled",
163                new Dictionary<string, object>
164                {
165                    ["enabled"] = enabled,
166                });
167
168        internal Task SetOfflineAsync(bool offline)
169            => Connection.SendMessageToServerAsync<PageChannel>(
170                Guid,
171                "setOffline",
172                new Dictionary<string, object>
173                {
174                    ["offline"] = offline,
175                });
176
177        internal async Task<IReadOnlyList<BrowserContextCookiesResult>> CookiesAsync(IEnumerable<string> urls)
178        {
179            return (await Connection.SendMessageToServerAsync(
180                Guid,
181                "cookies",
182                new Dictionary<string, object>
183                {
184                    ["urls"] = urls?.ToArray() ?? Array.Empty<string>(),
185                }).ConfigureAwait(false))?.GetProperty("cookies").ToObject<IReadOnlyList<BrowserContextCookiesResult>>();
186        }
187
188        internal Task AddCookiesAsync(IEnumerable<Cookie> cookies)
189            => Connection.SendMessageToServerAsync<PageChannel>(
190                Guid,
191                "addCookies",
192                new Dictionary<string, object>
193                {
194                    ["cookies"] = cookies,
195                });
196
197        internal Task GrantPermissionsAsync(IEnumerable<string> permissions, string origin)
198        {
199            var args = new Dictionary<string, object>
200            {
201                ["permissions"] = permissions?.ToArray(),
202            };
203
204            if (origin != null)
205            {
206                args["origin"] = origin;
207            }
208
209            return Connection.SendMessageToServerAsync<PageChannel>(Guid, "grantPermissions", args);
210        }
211
212        internal Task ClearPermissionsAsync() => Connection.SendMessageToServerAsync<PageChannel>(Guid, "clearPermissions", null);
213
214        internal Task SetGeolocationAsync(Geolocation geolocation)
215            => Connection.SendMessageToServerAsync<PageChannel>(
216                Guid,
217                "setGeolocation",
218                new Dictionary<string, object>
219                {
220                    ["geolocation"] = geolocation,
221                });
222
223        internal Task ClearCookiesAsync() => Connection.SendMessageToServerAsync<PageChannel>(Guid, "clearCookies", null);
224
225        internal Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)
226            => Connection.SendMessageToServerAsync(
227                Guid,
228                "setExtraHTTPHeaders",
229                new Dictionary<string, object>
230                {
231                    ["headers"] = headers.Select(kv => new HeaderEntry { Name = kv.Key, Value = kv.Value }),
232                });
233
234        internal Task<StorageState> GetStorageStateAsync()
235            => Connection.SendMessageToServerAsync<StorageState>(Guid, "storageState", null);
236
237        internal async Task<Artifact> HarExportAsync()
238        {
239            var result = await Connection.SendMessageToServerAsync(
240            Guid,
241            "harExport").ConfigureAwait(false);
242            return result.GetObject<Artifact>("artifact", Connection);
243        }
244
245        internal async Task<WritableStream> CreateTempFileAsync(string name)
246        {
247            var channelArgs = new Dictionary<string, object>
248            {
249                { "name", name },
250            };
251            var result = await Connection.SendMessageToServerAsync(Guid, "createTempFile", channelArgs).ConfigureAwait(false);
252            return result.GetObject<WritableStream>("writableStream", Connection);
253        }
254    }
255}
256
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 RouteChannel

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)