How to use SetRequestInterceptionAsync method of PuppeteerSharp.NetworkManager class

Best Puppeteer-sharp code snippet using PuppeteerSharp.NetworkManager.SetRequestInterceptionAsync

Page.cs

Source:Page.cs Github

copy

Full Screen

...147 /// </example>148 public event EventHandler<ResponseCreatedEventArgs> Response;149 /// <summary>150 /// Raised when a page issues a request. The <see cref="Request"/> object is read-only.151 /// In order to intercept and mutate requests, see <see cref="SetRequestInterceptionAsync(bool)"/>152 /// </summary>153 public event EventHandler<RequestEventArgs> Request;154 /// <summary>155 /// Raised when a request finishes successfully.156 /// </summary>157 public event EventHandler<RequestEventArgs> RequestFinished;158 /// <summary>159 /// Raised when a request fails, for example by timing out.160 /// </summary>161 public event EventHandler<RequestEventArgs> RequestFailed;162 /// <summary>163 /// Raised when an uncaught exception happens within the page.164 /// </summary>165 public event EventHandler<PageErrorEventArgs> PageError;166 ///// <summary>167 ///// Emitted when a dedicated WebWorker (<see href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"/>) is spawned by the page.168 ///// </summary>169 //public event EventHandler<WorkerEventArgs> WorkerCreated;170 ///// <summary>171 ///// Emitted when a dedicated WebWorker (<see href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"/>) is terminated.172 ///// </summary>173 //public event EventHandler<WorkerEventArgs> WorkerDestroyed;174 /// <summary>175 /// Raised when the page closes.176 /// </summary>177 public event EventHandler Close;178 /// <summary>179 /// Raised when the page opens a new tab or window.180 /// </summary>181 public event EventHandler<PopupEventArgs> Popup;182 /// <summary>183 /// This setting will change the default maximum time for the following methods:184 /// - <see cref="GoToAsync(string, NavigationOptions)"/>185 /// - <see cref="GoBackAsync(NavigationOptions)"/>186 /// - <see cref="GoForwardAsync(NavigationOptions)"/>187 /// - <see cref="ReloadAsync(NavigationOptions)"/>188 /// - <see cref="SetContentAsync(string, NavigationOptions)"/>189 /// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>190 /// **NOTE** <see cref="DefaultNavigationTimeout"/> takes priority over <seealso cref="DefaultTimeout"/>191 /// </summary>192 public int DefaultNavigationTimeout193 {194 get => _timeoutSettings.NavigationTimeout;195 set => _timeoutSettings.NavigationTimeout = value;196 }197 /// <summary>198 /// This setting will change the default maximum times for the following methods:199 /// - <see cref="GoBackAsync(NavigationOptions)"/>200 /// - <see cref="GoForwardAsync(NavigationOptions)"/>201 /// - <see cref="GoToAsync(string, NavigationOptions)"/>202 /// - <see cref="ReloadAsync(NavigationOptions)"/>203 /// - <see cref="SetContentAsync(string, NavigationOptions)"/>204 /// - <see cref="WaitForFunctionAsync(string, object[])"/>205 /// - <see cref="WaitForNavigationAsync(NavigationOptions)"/>206 /// - <see cref="WaitForRequestAsync(string, WaitForOptions)"/>207 /// - <see cref="WaitForResponseAsync(string, WaitForOptions)"/>208 /// - <see cref="WaitForXPathAsync(string, WaitForSelectorOptions)"/>209 /// - <see cref="WaitForSelectorAsync(string, WaitForSelectorOptions)"/>210 /// - <see cref="WaitForExpressionAsync(string, WaitForFunctionOptions)"/>211 /// </summary>212 public int DefaultTimeout213 {214 get => _timeoutSettings.Timeout;215 set => _timeoutSettings.Timeout = value;216 }217 /// <summary>218 /// Gets page's main frame219 /// </summary>220 /// <remarks>221 /// Page is guaranteed to have a main frame which persists during navigations.222 /// </remarks>223 public Frame MainFrame => FrameManager.MainFrame;224 /// <summary>225 /// Gets all frames attached to the page.226 /// </summary>227 /// <value>An array of all frames attached to the page.</value>228 public Frame[] Frames => FrameManager.GetFrames();229 ///// <summary>230 ///// Gets all workers in the page.231 ///// </summary>232 //public Worker[] Workers => _workers.Values.ToArray();233 /// <summary>234 /// Shortcut for <c>page.MainFrame.Url</c>235 /// </summary>236 public string Url => MainFrame.Url;237 /// <summary>238 /// Gets that target this page was created from.239 /// </summary>240 public Target Target { get; }241 /// <summary>242 /// Gets this page's keyboard243 /// </summary>244 public Keyboard Keyboard { get; }245 /// <summary>246 /// Gets this page's touchscreen247 /// </summary>248 public Touchscreen Touchscreen { get; }249 /// <summary>250 /// Gets this page's coverage251 /// </summary>252 public Coverage Coverage { get; }253 /// <summary>254 /// Gets this page's mouse255 /// </summary>256 public Mouse Mouse { get; }257 /// <summary>258 /// Gets this page's viewport259 /// </summary>260 public ViewPortOptions Viewport { get; private set; }261 /// <summary>262 /// List of supported metrics provided by the <see cref="Metrics"/> event.263 /// </summary>264 public static readonly IEnumerable<string> SupportedMetrics = new List<string>265 {266 "Timestamp",267 "Documents",268 "Frames",269 "JSEventListeners",270 "Nodes",271 "LayoutCount",272 "RecalcStyleCount",273 "LayoutDuration",274 "RecalcStyleDuration",275 "ScriptDuration",276 "TaskDuration",277 "JSHeapUsedSize",278 "JSHeapTotalSize"279 };280 /// <summary>281 /// Get the browser the page belongs to.282 /// </summary>283 public Browser Browser => Target.Browser;284 /// <summary>285 /// Get the browser context that the page belongs to.286 /// </summary>287 public BrowserContext BrowserContext => Target.BrowserContext;288 /// <summary>289 /// Get an indication that the page has been closed.290 /// </summary>291 public bool IsClosed { get; private set; }292 /// <summary>293 /// Gets the accessibility.294 /// </summary>295 public Accessibility Accessibility { get; }296 internal bool JavascriptEnabled { get; set; } = true;297 internal bool HasPopupEventListeners => Popup?.GetInvocationList().Any() == true;298 internal FrameManager FrameManager { get; private set; }299 private Task SessionClosedTask300 {301 get302 {303 if (_sessionClosedTcs == null)304 {305 _sessionClosedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);306 Client.Disconnected += clientDisconnected;307 void clientDisconnected(object sender, EventArgs e)308 {309 _sessionClosedTcs.TrySetException(new TargetClosedException("Target closed", "Session closed"));310 Client.Disconnected -= clientDisconnected;311 }312 }313 return _sessionClosedTcs.Task;314 }315 }316 #endregion317 #region Public Methods318 /// <summary>319 /// A utility function to be used with <see cref="Extensions.EvaluateFunctionAsync{T}(Task{JSHandle}, string, object[])"/>320 /// </summary>321 /// <param name="selector">A selector to query page for</param>322 /// <returns>Task which resolves to a <see cref="JSHandle"/> of <c>document.querySelectorAll</c> result</returns>323 public Task<JSHandle> QuerySelectorAllHandleAsync(string selector)324 => EvaluateFunctionHandleAsync("selector => Array.from(document.querySelectorAll(selector))", selector);325 /// <summary>326 /// Executes a script in browser context327 /// </summary>328 /// <param name="script">Script to be evaluated in browser context</param>329 /// <remarks>330 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.331 /// </remarks>332 /// <returns>Task which resolves to script return value</returns>333 public async Task<JSHandle> EvaluateExpressionHandleAsync(string script)334 {335 var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);336 return await context.EvaluateExpressionHandleAsync(script).ConfigureAwait(false);337 }338 /// <summary>339 /// Executes a script in browser context340 /// </summary>341 /// <param name="pageFunction">Script to be evaluated in browser context</param>342 /// <param name="args">Function arguments</param>343 /// <remarks>344 /// If the script, returns a Promise, then the method would wait for the promise to resolve and return its value.345 /// <see cref="JSHandle"/> instances can be passed as arguments346 /// </remarks>347 /// <returns>Task which resolves to script return value</returns>348 public async Task<JSHandle> EvaluateFunctionHandleAsync(string pageFunction, params object[] args)349 {350 var context = await MainFrame.GetExecutionContextAsync().ConfigureAwait(false);351 return await context.EvaluateFunctionHandleAsync(pageFunction, args).ConfigureAwait(false);352 }353 /// <summary>354 /// Activating request interception enables <see cref="Request.AbortAsync(RequestAbortErrorCode)">request.AbortAsync</see>, 355 /// <see cref="Request.ContinueAsync(Payload)">request.ContinueAsync</see> and <see cref="Request.RespondAsync(ResponseData)">request.RespondAsync</see> methods.356 /// </summary>357 /// <returns>The request interception task.</returns>358 /// <param name="value">Whether to enable request interception..</param>359 public Task SetRequestInterceptionAsync(bool value)360 => FrameManager.NetworkManager.SetRequestInterceptionAsync(value);361 /// <summary>362 /// Set offline mode for the page.363 /// </summary>364 /// <returns>Result task</returns>365 /// <param name="value">When <c>true</c> enables offline mode for the page.</param>366 public Task SetOfflineModeAsync(bool value) => FrameManager.NetworkManager.SetOfflineModeAsync(value);367 /// <summary>368 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content369 /// </summary>370 /// <param name="options">add script tag options</param>371 /// <remarks>372 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(options)</c>373 /// </remarks>374 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>...

Full Screen

Full Screen

NetworkManager.cs

Source:NetworkManager.cs Github

copy

Full Screen

...91 {92 _userCacheDisabled = !enabled;93 return UpdateProtocolCacheDisabledAsync();94 }95 internal Task SetRequestInterceptionAsync(bool value)96 {97 _userRequestInterceptionEnabled = value;98 return UpdateProtocolRequestInterceptionAsync();99 }100 #endregion101 #region Private Methods102 private Task UpdateProtocolCacheDisabledAsync()103 => _client.SendAsync("Network.setCacheDisabled", new NetworkSetCacheDisabledRequest104 {105 CacheDisabled = _userCacheDisabled || _protocolRequestInterceptionEnabled106 });107 private async void Client_MessageReceived(object sender, MessageEventArgs e)108 {109 try...

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 var browser = await Puppeteer.LaunchAsync(new LaunchOptions8 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"10 });11 var page = await browser.NewPageAsync();12 await page.SetRequestInterceptionAsync(true);13 page.Request += async (sender, e) =>14 {15 await e.Request.ContinueAsync();16 };17 }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23 static async Task Main(string[] args)24 {25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions26 {27 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"28 });29 var page = await browser.NewPageAsync();30 await page.SetRequestInterceptionAsync(true);31 page.Request += async (sender, e) =>32 {33 await e.Request.ContinueAsync();34 };35 }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40{41 static async Task Main(string[] args)42 {43 var browser = await Puppeteer.LaunchAsync(new LaunchOptions44 {45 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"46 });47 var page = await browser.NewPageAsync();48 await page.SetRequestInterceptionAsync(true);49 page.Request += async (sender, e) =>50 {51 await e.Request.ContinueAsync();52 };53 }54}

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3});4var page = await browser.NewPageAsync();5await page.SetRequestInterceptionAsync(true);6page.Request += async (sender, e) =>7{8 if (e.Request.ResourceType == ResourceType.Image)9 {10 await e.Request.AbortAsync();11 }12 {13 await e.Request.ContinueAsync();14 }15};16await page.WaitForNavigationAsync();17await page.ScreenshotAsync("google.png");18await browser.CloseAsync();

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--start-maximized" }4});5var page = await browser.NewPageAsync();6await page.SetViewportAsync(new ViewPortOptions7{8});9await page.SetRequestInterceptionAsync(true);10page.Request += async (sender, e) =>11{12 if (e.Request.ResourceType == ResourceType.Image)13 {14 await e.Request.AbortAsync();15 }16 {17 await e.Request.ContinueAsync();18 }19};20await page.ScreenshotAsync("2.png");21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24 Args = new string[] { "--start-maximized" }25});26var page = await browser.NewPageAsync();27await page.SetViewportAsync(new ViewPortOptions28{29});30await page.SetOfflineModeAsync(true);31await page.ScreenshotAsync("3.png");32await browser.CloseAsync();33var browser = await Puppeteer.LaunchAsync(new LaunchOptions34{35 Args = new string[] { "--start-maximized" }36});37var page = await browser.NewPageAsync();38await page.SetViewportAsync(new ViewPortOptions39{40});41await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36");42await page.ScreenshotAsync("4.png");43await browser.CloseAsync();

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 Args = new string[] { "--start-maximized" }15 });16 var page = await browser.NewPageAsync();17 await page.SetRequestInterceptionAsync(true);18 page.Request += Page_Request;19 await page.ScreenshotAsync("google.png");20 await browser.CloseAsync();21 }22 private static void Page_Request(object sender, PuppeteerSharp.RequestEventArgs e)23 {24 var request = e.Request;25 if (request.ResourceType == ResourceType.Image)26 {27 request.AbortAsync();28 }29 {30 request.ContinueAsync();31 }32 }33 }34}

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 }))12 using (var page = await browser.NewPageAsync())13 {14 await page.SetRequestInterceptionAsync(true);15 page.Request += async (sender, e) =>16 {17 await e.Request.ContinueAsync();18 };19 }20 }21 }22}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful