How to use SetRequestInterceptionAsync method of PuppeteerSharp.Page class

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

Methods.cs

Source:Methods.cs Github

copy

Full Screen

...155 private static void StopYoveProxyInternalServer(BotData data)156 => data.TryGetObject<ProxyClient>("puppeteer.yoveproxy")?.Dispose();157 private static async Task SetPageLoadingOptions(BotData data, PuppeteerSharp.Page page)158 {159 await page.SetRequestInterceptionAsync(true);160 page.Request += (sender, e) =>161 {162 // If we only want documents and scripts but the resource is not one of those, block163 if (data.ConfigSettings.PuppeteerSettings.LoadOnlyDocumentAndScript && 164 e.Request.ResourceType != ResourceType.Document && e.Request.ResourceType != ResourceType.Script)165 {166 e.Request.AbortAsync();167 }168 // If the url contains one of the blocked urls169 else if (data.ConfigSettings.PuppeteerSettings.BlockedUrls170 .Where(u => !string.IsNullOrWhiteSpace(u))171 .Any(u => e.Request.Url.Contains(u, StringComparison.OrdinalIgnoreCase)))172 {173 e.Request.AbortAsync();...

Full Screen

Full Screen

RequestContinueTests.cs

Source:RequestContinueTests.cs Github

copy

Full Screen

...20 }21 [Fact]22 public async Task ShouldWork()23 {24 await Page.SetRequestInterceptionAsync(true);25 Page.Request += async (sender, e) => await e.Request.ContinueAsync();26 await Page.GoToAsync(TestConstants.EmptyPage);27 }28 [Fact]29 public async Task ShouldAmendHTTPHeaders()30 {31 await Page.SetRequestInterceptionAsync(true);32 Page.Request += async (sender, e) =>33 {34 var headers = new Dictionary<string, string>(e.Request.Headers)35 {36 ["FOO"] = "bar"37 };38 await e.Request.ContinueAsync(new Payload { Headers = headers });39 };40 await Page.GoToAsync(TestConstants.EmptyPage);41 var requestTask = Server.WaitForRequest("/sleep.zzz", request => request.Headers["foo"].ToString());42 await Task.WhenAll(43 requestTask,44 Page.EvaluateExpressionAsync("fetch('/sleep.zzz')")45 );46 Assert.Equal("bar", requestTask.Result);47 }48 [Fact]49 public async Task ShouldRedirectInAWayNonObservableToPage()50 {51 await Page.SetRequestInterceptionAsync(true);52 Page.Request += async (sender, e) =>53 {54 var redirectURL = e.Request.Url.Contains("/empty.html")55 ? TestConstants.ServerUrl + "/consolelog.html" :56 null;57 await e.Request.ContinueAsync(new Payload { Url = redirectURL });58 };59 string consoleMessage = null;60 Page.Console += (sender, e) => consoleMessage = e.Message.Text;61 await Page.GoToAsync(TestConstants.EmptyPage);62 Assert.Equal(TestConstants.EmptyPage, Page.Url);63 Assert.Equal("yellow", consoleMessage);64 }65 [Fact]66 public async Task ShouldAmendMethodData()67 {68 await Page.GoToAsync(TestConstants.EmptyPage);69 await Page.SetRequestInterceptionAsync(true);70 Page.Request += async (sender, e) =>71 {72 await e.Request.ContinueAsync(new Payload { Method = HttpMethod.Post });73 };74 var requestTask = Server.WaitForRequest<string>("/sleep.zzz", request => request.Method);75 await Task.WhenAll(76 requestTask,77 Page.EvaluateExpressionAsync("fetch('/sleep.zzz')")78 );79 Assert.Equal("POST", requestTask.Result);80 }81 [Fact]82 public async Task ShouldAmendPostData()83 {84 await Page.SetRequestInterceptionAsync(true);85 Page.Request += async (sender, e) =>86 {87 await e.Request.ContinueAsync(new Payload88 {89 Method = HttpMethod.Post,90 PostData = "doggo"91 });92 };93 var requestTask = Server.WaitForRequest("/sleep.zzz", async request =>94 {95 using (var reader = new StreamReader(request.Body, Encoding.UTF8))96 {97 return await reader.ReadToEndAsync();98 }99 });100 await Task.WhenAll(101 requestTask,102 Page.GoToAsync(TestConstants.ServerUrl + "/sleep.zzz")103 );104 Assert.Equal("doggo", await requestTask.Result);105 }106 [Fact]107 public async Task ShouldAmendBothPostDataAndMethodOnNavigation()108 {109 await Page.SetRequestInterceptionAsync(true);110 Page.Request += async (sender, e) => await e.Request.ContinueAsync(new Payload111 {112 Method = HttpMethod.Post,113 PostData = "doggo"114 });115 var serverRequest = Server.WaitForRequest("/empty.html", req => new { req.Method, Body = new StreamReader(req.Body).ReadToEnd() });116 await Task.WhenAll(117 serverRequest,118 Page.GoToAsync(TestConstants.EmptyPage)119 );120 Assert.Equal(HttpMethod.Post.Method, serverRequest.Result.Method);121 Assert.Equal("doggo", serverRequest.Result.Body);122 }123 }...

Full Screen

Full Screen

NavigateLogin.cs

Source:NavigateLogin.cs Github

copy

Full Screen

...47 private async void SetPageAsync(Page page)48 {49 this.Page = page;50 //this.Page.Request += this.DenyRequests;51 //await this.Page.SetRequestInterceptionAsync(false);52 }53 private async Task InitialiseAsync()54 {55 if (this.Page == null)56 {57 throw new NullReferenceException("PuppeteerSharp.Page instance is null");58 }59 var response = await this.Page.GoToAsync(this.loginurl, new NavigationOptions60 {61 WaitUntil = new[] { WaitUntilNavigation.DOMContentLoaded },62 });63 this.elusername = await this.Page.QuerySelectorAsync("#user");64 this.elpassword = await this.Page.QuerySelectorAsync("input[name='password']");65 this.elbutton = await this.Page.QuerySelectorAsync("input.btn:nth-child(1)");66 if (this.elusername == null || this.elpassword == null || this.elbutton == null)67 {68 throw new Exception("NavigateLogin: Form input items missing.");69 }70 else71 {72 Console.WriteLine("Initialise Success.");73 }74 }75 private async Task ProcessAsync()76 {77 var usernameinput = await this.Page.QuerySelectorAsync("#user");78 await this.Page.EvaluateFunctionAsync($"yup => yup.value = '{this.Username}'", usernameinput);79 var passwordinput = await this.Page.QuerySelectorAsync("input[name='password']");80 await this.Page.EvaluateFunctionAsync($"mmhm => mmhm.value = '{this.Pasword}'", passwordinput);81 var form = await this.Page.QuerySelectorAsync("#loginForm");82 if (form == null)83 {84 throw new Exception("NavigateLogin: Page missing required login form.");85 }86 await this.Page.EvaluateFunctionAsync($"f => f.submit()", form);87 await this.Page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Load } });88 await this.Page.SetRequestInterceptionAsync(true);89 this.Page.Request += this.DenyRequests;90 }91 private async Task Commit()92 {93 // finalise operations94 if (this.Page.Url == "http://www.property-guru.co.nz/gurux/render.php?action=main")95 {96 // success97 this.cookies = await this.Page.GetCookiesAsync();98 }99 this.Page.Request -= this.DenyRequests;100 await this.Page.CloseAsync();101 this.Page = null;102 }...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...32 Headless = false33 });34 var page = await browser.NewPageAsync();35 //await page.SetExtraHttpHeadersAsync(new Dictionary<string, string>() { { "DNT","1"} });36 await page.SetRequestInterceptionAsync(true);37 await page.GoToAsync("https://whoer.net/");38 await page.ScreenshotAsync(@"screenshot.png");39 Console.WriteLine("done!");40 }41 /// <summary>42 /// Connect to a remote browser43 /// </summary>44 static async void RemoteUsage()45 {46 // launch chrome on windows via chrome.exe --remote-debugging-port=922247 // and go to http://localhost:9222/json/version48 // chrome.exe --remote-debugging-port=9222 --user-data-dir="e:\\cache" --no-default-browser-check --proxy-server="ip:port"49 /*50 * other args:...

Full Screen

Full Screen

PuppeteerEngine.cs

Source:PuppeteerEngine.cs Github

copy

Full Screen

...28 dic.Add("Accept-Encoding", "gzip, deflate, br");29 dic.Add("Accept-Language", "zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6");30 dic.Add("Connection", "keep-alive");31 await page.EmulateAsync(IPhone);32 await page.SetRequestInterceptionAsync(true);33 await page.SetExtraHttpHeadersAsync(dic);34 page.Request += async (sender, e) =>35 {36 if (e.Request.ResourceType == ResourceType.Image)37 await e.Request.AbortAsync();38 else39 await e.Request.ContinueAsync();40 };41 return page;42 }43 public async void launchBrowser(){44 _browser = await Puppeteer.LaunchAsync(new LaunchOptions45 {46 ExecutablePath = _settings.ChromePath,...

Full Screen

Full Screen

BlockResourcesPlugin.cs

Source:BlockResourcesPlugin.cs Github

copy

Full Screen

...27 return this;28 }29 public override async Task OnPageCreated(Page page)30 {31 await page.SetRequestInterceptionAsync(true);32 page.Request += (sender, args) => OnPageRequest(page, args);33 }34 private async void OnPageRequest(Page sender, RequestEventArgs e)35 {36 if (BlockResources.Any(rule => rule.IsRequestBlocked(sender, e.Request)))37 {38 await e.Request.AbortAsync();39 return;40 }41 await e.Request.ContinueAsync();42 }43 public override void BeforeLaunch(LaunchOptions options)44 {45 options.Args = options.Args.Append("--site-per-process").Append("--disable-features=IsolateOrigins").ToArray();...

Full Screen

Full Screen

BrowserMediaBlocker.cs

Source:BrowserMediaBlocker.cs Github

copy

Full Screen

...15 ResourceType.WebSocket16 };17 async Task DisableMedia(Page page)18 {19 await page.SetRequestInterceptionAsync(true);20 page.Request += async (obj, args) =>21 {22 var req = args.Request;23 var isBlacked = blacklist.Contains(req.ResourceType);24 if (isBlacked) await req.RespondAsync(new ResponseData {BodyData = new byte[0]});25 else await req.ContinueAsync();26 };27 }28 var pages = await browser.PagesAsync();29 foreach (var page in pages) await DisableMedia(page);30 browser.TargetCreated += async (obj1, args1) =>31 {32 try33 {...

Full Screen

Full Screen

PuppeteerConnection.cs

Source:PuppeteerConnection.cs Github

copy

Full Screen

...23 */24 }))25 using (var page = await browser.NewPageAsync())26 {27 //await page.SetRequestInterceptionAsync(true);28 await page.GoToAsync(url);29 await page.WaitForSelectorAsync(waitSelector);30 return await page.EvaluateFunctionAsync<T>(infoCode);31 }32 }33 }34}...

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2await page.SetRequestInterceptionAsync(true);3page.Request += async (sender, e) =>4{5 if (e.Request.ResourceType == ResourceType.Image)6 await e.Request.AbortAsync();7 await e.Request.ContinueAsync();8};9await page.ScreenshotAsync("google.png");10var page = await browser.NewPageAsync();11await page.SetRequestInterceptionAsync(true);12page.Request += async (sender, e) =>13{14 if (e.Request.ResourceType == ResourceType.Image)15 await e.Request.AbortAsync();16 await e.Request.ContinueAsync();17};18await page.ScreenshotAsync("google.png");19var page = await browser.NewPageAsync();20await page.SetRequestInterceptionAsync(true);21page.Request += async (sender, e) =>22{23 if (e.Request.ResourceType == ResourceType.Image)24 await e.Request.AbortAsync();25 await e.Request.ContinueAsync();26};27await page.ScreenshotAsync("google.png");28var page = await browser.NewPageAsync();29await page.SetRequestInterceptionAsync(true);30page.Request += async (sender, e) =>31{32 if (e.Request.ResourceType == ResourceType.Image)33 await e.Request.AbortAsync();34 await e.Request.ContinueAsync();35};36await page.ScreenshotAsync("google.png");37var page = await browser.NewPageAsync();38await page.SetRequestInterceptionAsync(true);39page.Request += async (sender, e) =>40{41 if (e.Request.ResourceType == ResourceType.Image)42 await e.Request.AbortAsync();43 await e.Request.ContinueAsync();44};45await page.ScreenshotAsync("

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using PuppeteerSharp;7using System.Threading;8using System.Net.Http;9using System.Net;10{11 {12 static void Main(string[] args)13 {14 MainAsync().Wait();15 }16 static async Task MainAsync()17 {18 var options = new LaunchOptions { Headless = false };19 var browser = await Puppeteer.LaunchAsync(options);20 var page = await browser.NewPageAsync();21 page.Request += Page_Request;22 }23 private static void Page_Request(object sender, RequestEventArgs e)24 {25 Console.WriteLine("Request: " + e.Request.Url);26 }27 }28}

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2await page.SetRequestInterceptionAsync(true);3page.Request += async (sender, e) =>4{5 var request = e.Request;6 if (request.ResourceType == ResourceType.Image)7 {8 await request.AbortAsync();9 }10 {11 await request.ContinueAsync();12 }13};14await page.ScreenshotAsync("google.png");15var page = await browser.NewPageAsync();16await page.SetRequestInterceptionAsync(true);17page.Request += async (sender, e) =>18{19 var request = e.Request;20 if (request.ResourceType == ResourceType.Image)21 {22 await request.AbortAsync();23 }24 {25 await request.ContinueAsync();26 }27};28await page.ScreenshotAsync("google.png");29var page = await browser.NewPageAsync();30await page.SetRequestInterceptionAsync(true);31page.Request += async (sender, e) =>32{33 var request = e.Request;34 if (request.ResourceType == ResourceType.Image)35 {36 await request.AbortAsync();37 }38 {39 await request.ContinueAsync();40 }41};42await page.ScreenshotAsync("google.png");43var page = await browser.NewPageAsync();44await page.SetRequestInterceptionAsync(true);45page.Request += async (sender, e) =>46{47 var request = e.Request;48 if (request.ResourceType == ResourceType.Image)49 {50 await request.AbortAsync();51 }52 {53 await request.ContinueAsync();54 }55};56await page.ScreenshotAsync("google.png");

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 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",10 };11 {12 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",13 };14 using (var browser = await Puppeteer.LaunchAsync(options))15 {16 using (var page = await browser.NewPageAsync())17 {

Full Screen

Full Screen

SetRequestInterceptionAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using System.IO;7using System.Net;8using System.Net.Http;9using System.Net.Http.Headers;10using System.Threading;11using PuppeteerSharp;12using PuppeteerSharp.Input;13using PuppeteerSharp.Helpers;14{15 {16 static void Main(string[] args)17 {18 MainAsync(args).GetAwaiter().GetResult();

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 {9 Args = new string[] { "--no-sandbox" }10 };11 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);12 using (var browser = await Puppeteer.LaunchAsync(options))13 {14 var page = await browser.NewPageAsync();15 await page.SetRequestInterceptionAsync(true);16 page.RequestCreated += async (sender, e) =>17 {18 await e.Request.ContinueAsync(new Payload { UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36" });19 };20 await page.ScreenshotAsync("google.png");21 Console.WriteLine("Screenshot taken");22 await browser.CloseAsync();23 }24 }25 }26}

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.

Most used method in Page

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful