How to use NetworkConditions class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.NetworkConditions

Page.cs

Source:Page.cs Github

copy

Full Screen

...584 /// <returns>Result task</returns>585 /// <remarks>586 /// **NOTE** This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644)587 /// </remarks>588 public Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions) => FrameManager.NetworkManager.EmulateNetworkConditionsAsync(networkConditions);589 /// <summary>590 /// Returns the page's cookies591 /// </summary>592 /// <param name="urls">Url's to return cookies for</param>593 /// <returns>Array of cookies</returns>594 /// <remarks>595 /// If no URLs are specified, this method returns cookies for the current page URL.596 /// If URLs are specified, only cookies for those URLs are returned.597 /// </remarks>598 public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)599 => (await Client.SendAsync<NetworkGetCookiesResponse>("Network.getCookies", new NetworkGetCookiesRequest600 {601 Urls = urls.Length > 0 ? urls : new string[] { Url }602 }).ConfigureAwait(false)).Cookies;...

Full Screen

Full Screen

NetworkManager.cs

Source:NetworkManager.cs Github

copy

Full Screen

...13 private readonly CDPSession _client;14 private readonly ILogger _logger;15 private readonly ConcurrentSet<string> _attemptedAuthentications = new();16 private readonly bool _ignoreHTTPSErrors;17 private readonly InternalNetworkConditions _emulatedNetworkConditions = new()18 {19 Offline = false,20 Upload = -1,21 Download = -1,22 Latency = 0,23 };24 private readonly NetworkEventManager _networkEventManager = new();25 private Dictionary<string, string> _extraHTTPHeaders;26 private Credentials _credentials;27 private bool _userRequestInterceptionEnabled;28 private bool _userCacheDisabled;29 private bool _protocolRequestInterceptionEnabled;30 internal NetworkManager(CDPSession client, bool ignoreHTTPSErrors, FrameManager frameManager)31 {32 FrameManager = frameManager;33 _client = client;34 _ignoreHTTPSErrors = ignoreHTTPSErrors;35 _client.MessageReceived += Client_MessageReceived;36 _logger = _client.Connection.LoggerFactory.CreateLogger<NetworkManager>();37 }38 internal event EventHandler<ResponseCreatedEventArgs> Response;39 internal event EventHandler<RequestEventArgs> Request;40 internal event EventHandler<RequestEventArgs> RequestFinished;41 internal event EventHandler<RequestEventArgs> RequestFailed;42 internal event EventHandler<RequestEventArgs> RequestServedFromCache;43 internal Dictionary<string, string> ExtraHTTPHeaders => _extraHTTPHeaders?.Clone();44 internal FrameManager FrameManager { get; set; }45 internal int NumRequestsInProgress => _networkEventManager.NumRequestsInProgress;46 internal async Task InitializeAsync()47 {48 await _client.SendAsync("Network.enable").ConfigureAwait(false);49 if (_ignoreHTTPSErrors)50 {51 await _client.SendAsync("Security.setIgnoreCertificateErrors", new SecuritySetIgnoreCertificateErrorsRequest52 {53 Ignore = true54 }).ConfigureAwait(false);55 }56 }57 internal Task AuthenticateAsync(Credentials credentials)58 {59 _credentials = credentials;60 return UpdateProtocolRequestInterceptionAsync();61 }62 internal Task SetExtraHTTPHeadersAsync(Dictionary<string, string> extraHTTPHeaders)63 {64 _extraHTTPHeaders = new Dictionary<string, string>();65 foreach (var item in extraHTTPHeaders)66 {67 _extraHTTPHeaders[item.Key.ToLower(CultureInfo.CurrentCulture)] = item.Value;68 }69 return _client.SendAsync("Network.setExtraHTTPHeaders", new NetworkSetExtraHTTPHeadersRequest70 {71 Headers = _extraHTTPHeaders72 });73 }74 internal async Task SetOfflineModeAsync(bool value)75 {76 _emulatedNetworkConditions.Offline = value;77 await UpdateNetworkConditionsAsync().ConfigureAwait(false);78 }79 internal async Task EmulateNetworkConditionsAsync(NetworkConditions networkConditions)80 {81 _emulatedNetworkConditions.Upload = networkConditions?.Upload ?? -1;82 _emulatedNetworkConditions.Download = networkConditions?.Download ?? -1;83 _emulatedNetworkConditions.Latency = networkConditions?.Latency ?? 0;84 await UpdateNetworkConditionsAsync().ConfigureAwait(false);85 }86 private Task UpdateNetworkConditionsAsync()87 => _client.SendAsync("Network.emulateNetworkConditions", new NetworkEmulateNetworkConditionsRequest88 {89 Offline = _emulatedNetworkConditions.Offline,90 Latency = _emulatedNetworkConditions.Latency,91 UploadThroughput = _emulatedNetworkConditions.Upload,92 DownloadThroughput = _emulatedNetworkConditions.Download,93 });94 internal Task SetUserAgentAsync(string userAgent)95 => _client.SendAsync("Network.setUserAgentOverride", new NetworkSetUserAgentOverrideRequest96 {97 UserAgent = userAgent98 });99 internal Task SetCacheEnabledAsync(bool enabled)100 {101 _userCacheDisabled = !enabled;102 return UpdateProtocolCacheDisabledAsync();103 }104 internal Task SetRequestInterceptionAsync(bool value)105 {106 _userRequestInterceptionEnabled = value;...

Full Screen

Full Screen

Puppeteer.cs

Source:Puppeteer.cs Github

copy

Full Screen

...39 /// </code>40 /// </example>41 public static IReadOnlyDictionary<DeviceDescriptorName, DeviceDescriptor> Devices => DeviceDescriptors.ToReadOnly();42 /// <summary>43 /// Returns a list of network conditions to be used with <seealso cref="Page.EmulateNetworkConditionsAsync(NetworkConditions)"/>.44 /// Actual list of conditions can be found in <seealso cref="PredefinedNetworkConditions.Conditions"/>.45 /// </summary>46 /// <example>47 /// <code>48 ///<![CDATA[49 /// var slow3G = Puppeteer.NetworkConditions["Slow 3G"];50 /// using(var page = await browser.NewPageAsync())51 /// {52 /// await page.EmulateNetworkConditionsAsync(slow3G);53 /// await page.goto('https://www.google.com');54 /// }55 /// ]]>56 /// </code>57 /// </example>58 public static IReadOnlyDictionary<string, NetworkConditions> NetworkConditions => PredefinedNetworkConditions.ToReadOnly();59 /// <summary>60 /// Returns an array of argument based on the options provided and the platform where the library is running61 /// </summary>62 /// <returns>Chromium arguments.</returns>63 /// <param name="options">Options.</param>64 public static string[] GetDefaultArgs(LaunchOptions options = null)65 => (options?.Product ?? Product.Chrome) == Product.Chrome66 ? ChromiumLauncher.GetDefaultArgs(options ?? new LaunchOptions())67 : FirefoxLauncher.GetDefaultArgs(options ?? new LaunchOptions());68 /// <summary>69 /// The method launches a browser instance with given arguments. The browser will be closed when the Browser is disposed.70 /// </summary>71 /// <param name="options">Options for launching Chrome</param>72 /// <param name="loggerFactory">The logger factory</param>...

Full Screen

Full Screen

PageEmulateNetworkConditionsTests.cs

Source:PageEmulateNetworkConditionsTests.cs Github

copy

Full Screen

...5using Xunit.Abstractions;6namespace PuppeteerSharp.Tests.EmulationTests7{8 [Collection(TestConstants.TestFixtureCollectionName)]9 public class PageEmulateNetworkConditionsTests : PuppeteerPageBaseTest10 {11 public PageEmulateNetworkConditionsTests(ITestOutputHelper output) : base(output)12 {13 }14 [PuppeteerTest("emulation.spec.ts", "Page.emulateNetworkConditions", "should change navigator.connection.effectiveType")]15 [SkipBrowserFact(skipFirefox: true)]16 public async Task ShouldChangeNavigatorConnectionEffectiveType()17 {18 var slow3G = Puppeteer.NetworkConditions[NetworkConditions.Slow3G];19 var fast3G = Puppeteer.NetworkConditions[NetworkConditions.Fast3G];20 Assert.Equal("4g", await Page.EvaluateExpressionAsync<string>("window.navigator.connection.effectiveType").ConfigureAwait(false));21 await Page.EmulateNetworkConditionsAsync(fast3G);22 Assert.Equal("3g", await Page.EvaluateExpressionAsync<string>("window.navigator.connection.effectiveType").ConfigureAwait(false));23 await Page.EmulateNetworkConditionsAsync(slow3G);24 Assert.Equal("2g", await Page.EvaluateExpressionAsync<string>("window.navigator.connection.effectiveType").ConfigureAwait(false));25 await Page.EmulateNetworkConditionsAsync(null);26 }27 }28}...

Full Screen

Full Screen

PredefinedNetworkConditions.cs

Source:PredefinedNetworkConditions.cs Github

copy

Full Screen

...5{6 /// <summary>7 /// Predefined network conditions.8 /// </summary>9 public static class PredefinedNetworkConditions10 {11 private static readonly Dictionary<string, NetworkConditions> Conditions = new Dictionary<string, NetworkConditions>12 {13 [NetworkConditions.Slow3G] = new NetworkConditions14 {15 Download = ((500 * 1000) / 8) * 0.8,16 Upload = ((500 * 1000) / 8) * 0.8,17 Latency = 400 * 5,18 },19 [NetworkConditions.Fast3G] = new NetworkConditions20 {21 Download = ((1.6 * 1000 * 1000) / 8) * 0.9,22 Upload = ((750 * 1000) / 8) * 0.9,23 Latency = 150 * 3.75,24 },25 };26 private static Lazy<IReadOnlyDictionary<string, NetworkConditions>> _readOnlyConditions =27 new Lazy<IReadOnlyDictionary<string, NetworkConditions>>(() => new ReadOnlyDictionary<string, NetworkConditions>(Conditions));28 internal static IReadOnlyDictionary<string, NetworkConditions> ToReadOnly() => _readOnlyConditions.Value;29 }30}...

Full Screen

Full Screen

NetworkConditions.cs

Source:NetworkConditions.cs Github

copy

Full Screen

1namespace PuppeteerSharp2{3 /// <summary>4 /// Options to be used in <see cref="Page.EmulateNetworkConditionsAsync(NetworkConditions)"/>5 /// </summary>6 public class NetworkConditions7 {8 /// <summary>9 /// Key to be used with <see cref="Puppeteer.NetworkConditions()"/>10 /// </summary>11 public const string Slow3G = "Slow 3G";12 /// <summary>13 /// Key to be used with <see cref="Puppeteer.NetworkConditions()"/>14 /// </summary>15 public const string Fast3G = "Fast 3G";16 /// <summary>17 /// Download speed (bytes/s), `-1` to disable18 /// </summary>19 public double Download { get; set; } = -1;20 /// <summary>21 /// Upload speed (bytes/s), `-1` to disable22 /// </summary>23 public double Upload { get; set; } = -1;24 /// <summary>25 /// Latency (ms), `0` to disable26 /// </summary>27 public double Latency { get; set; } = 0;...

Full Screen

Full Screen

InternalNetworkConditions.cs

Source:InternalNetworkConditions.cs Github

copy

Full Screen

1namespace PuppeteerSharp2{3 internal class InternalNetworkConditions : NetworkConditions4 {5 public bool Offline { get; set; }6 }7}...

Full Screen

Full Screen

NetworkConditions

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.SetRequestInterceptionAsync(true);14 page.Request += async (sender, e) =>15 {16 var request = e.Request;17 if (request.ResourceType == ResourceType.Image)18 {19 await request.AbortAsync();20 }21 {22 await request.ContinueAsync();23 }24 };25 await page.EvaluateFunctionAsync("() => alert('yo!')");26 await page.WaitForSelectorAsync("img");27 await page.WaitForSelectorAsync("img");28 await page.WaitForSelectorAsync("img");29 await page.WaitForSelectorAsync("img");30 await page.WaitForSelectorAsync("img");31 await page.WaitForSelectorAsync("img");32 await page.WaitForSelectorAsync("img");33 await page.WaitForSelectorAsync("img");34 await page.WaitForSelectorAsync("img");35 await page.WaitForSelectorAsync("img");36 await page.WaitForSelectorAsync("img");37 await page.WaitForSelectorAsync("img");38 await page.WaitForSelectorAsync("img");39 await page.WaitForSelectorAsync("img");

Full Screen

Full Screen

NetworkConditions

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 Args = new string[] { "--start-maximized" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 {16 };17 await page.SetRequestInterceptionAsync(true);18 page.Request += async (sender, e) =>19 {20 await e.Request.ContinueAsync(networkConditions);21 };22 }23 }24 }25 }26}

Full Screen

Full Screen

NetworkConditions

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2var browserFetcher = new BrowserFetcher();3await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);4var browser = await Puppeteer.LaunchAsync(new LaunchOptions5{6 Args = new string[] { "--no-sandbox" }7});8var page = await browser.NewPageAsync();9await page.SetRequestInterceptionAsync(true);10page.Request += async (sender, e) => await page.SetExtraHTTPHeadersAsync(new Dictionary<string, string>11{12 { "Accept-Language", "en-US,en;q=0.5" }13});14await page.SetOfflineModeAsync(true);15await page.SetGeolocationAsync(new Geolocation16{17});18var client = await page.Target.CreateCDPSessionAsync();19await client.SendAsync("Network.enable");20await client.SendAsync("Network.emulateNetworkConditions", new21{22});23await page.SetOfflineModeAsync(false);24await page.SetGeolocationAsync(new Geolocation25{26});27await page.CloseAsync();28await browser.CloseAsync();29using PuppeteerSharp;30var browserFetcher = new BrowserFetcher();31await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);32var browser = await Puppeteer.LaunchAsync(new LaunchOptions33{34 Args = new string[] { "--no-sandbox" }35});36var page = await browser.NewPageAsync();37await page.SetRequestInterceptionAsync(true);38page.Request += async (sender, e) => await page.SetExtraHTTPHeadersAsync(new Dictionary<string, string>39{40 { "Accept-Language", "en-US,en;q=0.5" }41});42await page.SetOfflineModeAsync(true);43await page.SetGeolocationAsync(new Geolocation44{

Full Screen

Full Screen

NetworkConditions

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System.Threading.Tasks;3using System;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 Args = new string[] { "--no-sandbox" }13 });14 var page = await browser.NewPageAsync();15 await page.SetRequestInterceptionAsync(true);16 await page.SetOfflineModeAsync(true);17 Console.WriteLine("Done");18 }19 }20}21using PuppeteerSharp;22using System.Threading.Tasks;23using System;24{25 {26 static async Task Main(string[] args)27 {28 Console.WriteLine("Hello World!");29 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);30 var browser = await Puppeteer.LaunchAsync(new LaunchOptions31 {32 Args = new string[] { "--no-sandbox" }33 });34 var page = await browser.NewPageAsync();35 await page.SetRequestInterceptionAsync(true);36 await page.SetOfflineModeAsync(true);37 Console.WriteLine("Done");38 }39 }40}41using PuppeteerSharp;42using System.Threading.Tasks;43using System;44{45 {46 static async Task Main(string[] args)47 {48 Console.WriteLine("Hello World!");49 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);50 var browser = await Puppeteer.LaunchAsync(new LaunchOptions51 {52 Args = new string[] { "--no-sandbox" }53 });54 var page = await browser.NewPageAsync();55 await page.SetRequestInterceptionAsync(true);56 await page.SetOfflineModeAsync(true);57 Console.WriteLine("Done");58 }59 }60}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful