Best Puppeteer-sharp code snippet using PuppeteerSharp.AddTagOptions
ChromeClient.cs
Source:ChromeClient.cs
...123 DefaultViewport = null124 };125 Browser = extra.LaunchAsync(options).Result;126 Page = Browser.PagesAsync().Result[0];127 Page.AddScriptTagAsync(new AddTagOptions128 {129 Content = Resources.base64130 }).Wait();131 Page.AddScriptTagAsync(new AddTagOptions132 {133 Content = Resources.hashes_min134 }).Wait();135 Page.AddScriptTagAsync(new AddTagOptions136 {137 Content = Resources.jsbn138 }).Wait();139 Page.AddScriptTagAsync(new AddTagOptions140 {141 Content = Resources.jsbn2142 }).Wait();143 Page.AddScriptTagAsync(new AddTagOptions144 {145 Content = Resources.scrypt146 }).Wait();147 Page.AddScriptTagAsync(new AddTagOptions148 {149 Content = Resources.srp150 }).Wait();151 Page.AddScriptTagAsync(new AddTagOptions152 {153 Content = Resources.chrome_client154 }).Wait();155 IsReady = true;156 return this;157 }158 }159}...
SetBypassCSPTests.cs
Source:SetBypassCSPTests.cs
...16 public async Task ShouldBypassCSPMetaTag()17 {18 // Make sure CSP prohibits addScriptTag.19 await Page.GoToAsync(TestConstants.ServerUrl + "/csp.html");20 await Page.AddScriptTagAsync(new AddTagOptions21 {22 Content = "window.__injected = 42;"23 }).ContinueWith(_ => Task.CompletedTask);24 Assert.Null(await Page.EvaluateExpressionAsync("window.__injected"));25 // By-pass CSP and try one more time.26 await Page.SetBypassCSPAsync(true);27 await Page.ReloadAsync();28 await Page.AddScriptTagAsync(new AddTagOptions29 {30 Content = "window.__injected = 42;"31 });32 Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));33 }34 [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass CSP header")]35 [SkipBrowserFact(skipFirefox: true)]36 public async Task ShouldBypassCSPHeader()37 {38 // Make sure CSP prohibits addScriptTag.39 Server.SetCSP("/empty.html", "default-src 'self'");40 await Page.GoToAsync(TestConstants.EmptyPage);41 await Page.AddScriptTagAsync(new AddTagOptions42 {43 Content = "window.__injected = 42;"44 }).ContinueWith(_ => Task.CompletedTask);45 Assert.Null(await Page.EvaluateExpressionAsync("window.__injected"));46 // By-pass CSP and try one more time.47 await Page.SetBypassCSPAsync(true);48 await Page.ReloadAsync();49 await Page.AddScriptTagAsync(new AddTagOptions50 {51 Content = "window.__injected = 42;"52 });53 Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));54 }55 [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass after cross-process navigation")]56 [SkipBrowserFact(skipFirefox: true)]57 public async Task ShouldBypassAfterCrossProcessNavigation()58 {59 await Page.SetBypassCSPAsync(true);60 await Page.GoToAsync(TestConstants.ServerUrl + "/csp.html");61 await Page.AddScriptTagAsync(new AddTagOptions62 {63 Content = "window.__injected = 42;"64 });65 Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));66 await Page.GoToAsync(TestConstants.CrossProcessUrl + "/csp.html");67 await Page.AddScriptTagAsync(new AddTagOptions68 {69 Content = "window.__injected = 42;"70 });71 Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));72 }73 [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass CSP in iframes as well")]74 [SkipBrowserFact(skipFirefox: true)]75 public async Task ShouldBypassCSPInIframesAsWell()76 {77 await Page.GoToAsync(TestConstants.EmptyPage);78 // Make sure CSP prohibits addScriptTag in an iframe.79 var frame = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.ServerUrl + "/csp.html");80 await frame.AddScriptTagAsync(new AddTagOptions81 {82 Content = "window.__injected = 42;"83 }).ContinueWith(_ => Task.CompletedTask);84 Assert.Null(await frame.EvaluateFunctionAsync<int?>("() => window.__injected"));85 // By-pass CSP and try one more time.86 await Page.SetBypassCSPAsync(true);87 await Page.ReloadAsync();88 // Make sure CSP prohibits addScriptTag in an iframe.89 frame = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.ServerUrl + "/csp.html");90 await frame.AddScriptTagAsync(new AddTagOptions91 {92 Content = "window.__injected = 42;"93 }).ContinueWith(_ => Task.CompletedTask);94 Assert.Equal(42, await frame.EvaluateFunctionAsync<int?>("() => window.__injected"));95 }96 }97}...
DocumentsController.cs
Source:DocumentsController.cs
...61 headers.Add("Accept-Charset", "utf-8");62 headers.Add("Content-Type", "text/html; charset=utf-8");63 var response = await page.GoToAsync("data:text/html," + documentData.PdfBodyHTML, WaitUntilNavigation.Networkidle0);64 await page.SetContentAsync(Encoding.UTF8.GetString(await response.BufferAsync()));65 await page.AddStyleTagAsync(new AddTagOptions { Url = documentData.PdfCssUrl });66 67 await page.SetExtraHttpHeadersAsync(headers);68 await page.EvaluateExpressionAsync("window.scrollBy(0, window.innerHeight);");69 MarginOptions marginOption;70 if (documentData.DocumentMargin == null)71 {72 marginOption = new MarginOptions73 {74 Top = _configuration.GetSection("AppSettings:Margin:Top").Value,75 Bottom = _configuration.GetSection("AppSettings:Margin:Bottom").Value,76 Left = _configuration.GetSection("AppSettings:Margin:Left").Value,77 Right = _configuration.GetSection("AppSettings:Margin:Right").Value78 };79 }...
AddStyleTagTests.cs
Source:AddStyleTagTests.cs
...14 [Fact]15 public async Task ShouldThrowAnErrorIfNoOptionsAreProvided()16 {17 var exception = await Assert.ThrowsAsync<ArgumentException>(()18 => Page.AddStyleTagAsync(new AddTagOptions()));19 Assert.Equal("Provide options with a `Url`, `Path` or `Content` property", exception.Message);20 }21 [Fact]22 public async Task ShouldWorkWithAUrl()23 {24 await Page.GoToAsync(TestConstants.EmptyPage);25 var styleHandle = await Page.AddStyleTagAsync(new AddTagOptions { Url = "/injectedstyle.css" });26 Assert.NotNull(styleHandle as ElementHandle);27 Assert.Equal("rgb(255, 0, 0)", await Page.EvaluateExpressionAsync(28 "window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"));29 }30 [Fact]31 public async Task ShouldThrowAnErrorIfLoadingFromUrlFail()32 {33 await Page.GoToAsync(TestConstants.EmptyPage);34 var exception = await Assert.ThrowsAsync<PuppeteerException>(()35 => Page.AddStyleTagAsync(new AddTagOptions { Url = "/nonexistfile.js" }));36 Assert.Equal("Loading style from /nonexistfile.js failed", exception.Message);37 }38 [Fact]39 public async Task ShouldWorkWithAPath()40 {41 await Page.GoToAsync(TestConstants.EmptyPage);42 var styleHandle = await Page.AddStyleTagAsync(new AddTagOptions { Path = "assets/injectedstyle.css" });43 Assert.NotNull(styleHandle as ElementHandle);44 Assert.Equal("rgb(255, 0, 0)", await Page.EvaluateExpressionAsync(45 "window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"));46 }47 [Fact]48 public async Task ShouldIncludeSourcemapWhenPathIsProvided()49 {50 await Page.GoToAsync(TestConstants.EmptyPage);51 await Page.AddStyleTagAsync(new AddTagOptions52 {53 Path = Path.Combine(Directory.GetCurrentDirectory(), Path.Combine("assets", "injectedstyle.css"))54 });55 var styleHandle = await Page.QuerySelectorAsync("style");56 var styleContent = await Page.EvaluateFunctionAsync<string>("style => style.innerHTML", styleHandle);57 Assert.Contains(Path.Combine("assets", "injectedstyle.css"), styleContent);58 }59 [Fact]60 public async Task ShouldWorkWithContent()61 {62 await Page.GoToAsync(TestConstants.EmptyPage);63 var styleHandle = await Page.AddStyleTagAsync(new AddTagOptions { Content = "body { background-color: green; }" });64 Assert.NotNull(styleHandle as ElementHandle);65 Assert.Equal("rgb(0, 128, 0)", await Page.EvaluateExpressionAsync(66 "window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"));67 }68 }69}
AddScriptTagTests.cs
Source:AddScriptTagTests.cs
...14 [Fact]15 public async Task ShouldThrowAnErrorIfNoOptionsAreProvided()16 {17 var exception = await Assert.ThrowsAsync<ArgumentException>(()18 => Page.AddScriptTagAsync(new AddTagOptions()));19 Assert.Equal("Provide options with a `Url`, `Path` or `Content` property", exception.Message);20 }21 [Fact]22 public async Task ShouldWorkWithAUrl()23 {24 await Page.GoToAsync(TestConstants.EmptyPage);25 var scriptHandle = await Page.AddScriptTagAsync(new AddTagOptions { Url = "/injectedfile.js" });26 Assert.NotNull(scriptHandle as ElementHandle);27 Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("__injected"));28 }29 [Fact]30 public async Task ShouldThrowAnErrorIfLoadingFromUrlFail()31 {32 await Page.GoToAsync(TestConstants.EmptyPage);33 var exception = await Assert.ThrowsAsync<PuppeteerException>(()34 => Page.AddScriptTagAsync(new AddTagOptions { Url = "/nonexistfile.js" }));35 Assert.Equal("Loading script from /nonexistfile.js failed", exception.Message);36 }37 [Fact]38 public async Task ShouldWorkWithAPath()39 {40 await Page.GoToAsync(TestConstants.EmptyPage);41 var scriptHandle = await Page.AddScriptTagAsync(new AddTagOptions42 {43 Path = Path.Combine(Directory.GetCurrentDirectory(), Path.Combine("assets", "injectedfile.js"))44 });45 Assert.NotNull(scriptHandle as ElementHandle);46 Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("__injected"));47 }48 [Fact]49 public async Task ShouldIncludeSourcemapWhenPathIsProvided()50 {51 await Page.GoToAsync(TestConstants.EmptyPage);52 await Page.AddScriptTagAsync(new AddTagOptions53 {54 Path = Path.Combine(Directory.GetCurrentDirectory(), Path.Combine("assets", "injectedfile.js"))55 });56 var result = await Page.EvaluateExpressionAsync<string>("__injectedError.stack");57 Assert.Contains(Path.Combine("assets", "injectedfile.js"), result);58 }59 [Fact]60 public async Task ShouldWorkWithContent()61 {62 await Page.GoToAsync(TestConstants.EmptyPage);63 var scriptHandle = await Page.AddScriptTagAsync(new AddTagOptions { Content = "window.__injected = 35;" });64 Assert.NotNull(scriptHandle as ElementHandle);65 Assert.Equal(35, await Page.EvaluateExpressionAsync<int>("__injected"));66 }67 }68}...
PuppeteerExtensions.cs
Source:PuppeteerExtensions.cs
...27 try28 {29 foreach (var jsFile in jsScripts)30 {31 await page.AddScriptTagAsync(new AddTagOptions32 {33 Path = $"ClientScripts/{jsFile}"34 }); ;35 }36 }37 catch { }38 };39 }40 return page;41 }42 public static async Task<Response> GoToWithRetryAsync(this Page page, string url, int maxRetries, NavigationOptions navigationOptions)43 {44 var loaded = false;45 var attempt = 1;...
PdfRequest.cs
Source:PdfRequest.cs
...30 /// <summary>31 /// Add script tags. See [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#frameaddscripttagoptions)32 /// You can also add script tags in HTML33 /// </summary>34 public List<AddTagOptions>? AddScriptTags { get; set; }35 /// <summary>36 /// Add style tags. See [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#frameaddstyletagoptions)37 /// You can also add style tags in HTML38 /// </summary>39 public List<AddTagOptions>? AddStyleTags { get; set; }40 }41 }42}...
AddTagOptions.cs
Source:AddTagOptions.cs
1namespace PuppeteerSharp2{3 /// <summary>4 /// Options used by <see cref="Page.AddScriptTagAsync(AddTagOptions)"/> & <see cref="Page.AddStyleTagAsync(AddTagOptions)"/>5 /// </summary>6 public class AddTagOptions7 {8 /// <summary>9 /// Url of a script to be added10 /// </summary>11 public string Url { get; set; }12 /// <summary>13 /// Path to the JavaScript file to be injected into frame. If its a relative path, then it is resolved relative to <see cref="System.IO.Directory.GetCurrentDirectory"/>14 /// </summary>15 public string Path { get; set; }16 /// <summary>17 /// Raw JavaScript content to be injected into frame18 /// </summary>19 public string Content { get; set; }20 }...
AddTagOptions
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 {13 };14 using (var browser = await Puppeteer.LaunchAsync(options))15 using (var page = await browser.NewPageAsync())16 {17 var element = await page.QuerySelectorAsync("input[name=q]");18 await element.TypeAsync("puppeteer-sharp");19 await element.PressAsync("Enter");20 await page.WaitForNavigationAsync();21 await page.ScreenshotAsync("google.png");22 }23 }24 }25}26using PuppeteerSharp;27using System;28using System.Threading.Tasks;29{30 {31 static void Main(string[] args)32 {33 MainAsync().GetAwaiter().GetResult();34 }35 static async Task MainAsync()36 {37 {38 };39 using (var browser = await Puppeteer.LaunchAsync(options))40 using (var page = await browser.NewPageAsync())41 {42 var element = await page.QuerySelectorAsync("input[name=q]");43 await element.TypeAsync("puppeteer-sharp");44 await element.PressAsync("Enter");45 await page.WaitForNavigationAsync();46 await page.ScreenshotAsync("google.png");47 }48 }49 }50}51using PuppeteerSharp;52using System;53using System.Threading.Tasks;54{55 {56 static void Main(string[] args)57 {58 MainAsync().GetAwaiter().GetResult();59 }60 static async Task MainAsync()61 {62 {63 };64 using (var browser = await Puppeteer.LaunchAsync(options))65 using (var page = await browser.NewPageAsync())66 {
AddTagOptions
Using AI Code Generation
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 {13 };14 using (var browser = await Puppeteer.LaunchAsync(options))15 using (var page = await browser.NewPageAsync())16 {17 await page.AddScriptTagAsync(new AddTagOptions18 {19 });20 await page.AddScriptTagAsync(new AddTagOptions21 {22 });23 await page.AddScriptTagAsync(new AddTagOptions24 {25 Content = "console.log('hello, world!');"26 });27 await page.AddStyleTagAsync(new AddTagOptions28 {29 });30 await page.AddStyleTagAsync(new AddTagOptions31 {32 });33 await page.AddStyleTagAsync(new AddTagOptions34 {35 Content = "body { background-color: green; }"36 });37 }38 }39 }40}41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch({ headless: false, defaultViewport: null });44 const page = await browser.newPage();45 await page.addScriptTag({ path: 'path/to/file.js' });46 await page.addScriptTag({ content: 'console.log("hello, world!");' });
AddTagOptions
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }4});5var page = await browser.NewPageAsync();6await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });7await page.WaitForSelectorAsync("input[name='q']");8await page.TypeAsync("input[name='q']", "Puppeteer");9await page.WaitForSelectorAsync("input[name='btnK']");10await page.ClickAsync("input[name='btnK']");11await page.WaitForNavigationAsync();12await page.ScreenshotAsync("screenshot.png");13await browser.CloseAsync();14var browser = await Puppeteer.LaunchAsync(new LaunchOptions15{16 Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }17});18var page = await browser.NewPageAsync();19await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });20await page.WaitForSelectorAsync("input[name='q']");21await page.TypeAsync("input[name='q']", "Puppeteer");22await page.WaitForSelectorAsync("input[name='btnK']");23await page.ClickAsync("input[name='btnK']");24await page.WaitForNavigationAsync();25await page.ScreenshotAsync("screenshot.png");26await browser.CloseAsync();27var browser = await Puppeteer.LaunchAsync(new LaunchOptions28{29 Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }30});31var page = await browser.NewPageAsync();32await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });33await page.WaitForSelectorAsync("input[name='q']");34await page.TypeAsync("input[name='q']", "Puppeteer");35await page.WaitForSelectorAsync("input[name='btnK']");36await page.ClickAsync("input[name='btnK']");37await page.WaitForNavigationAsync();38await page.ScreenshotAsync("screenshot.png");
AddTagOptions
Using AI Code Generation
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 });15 var page = await browser.NewPageAsync();16 await page.AddScriptTagAsync(new AddTagOptions17 {18 });19 await browser.CloseAsync();20 }21 }22}23Related Posts: AddScriptTagAsync() method in PuppeteerSharp24AddStyleTagAsync() method in PuppeteerSharp25EvaluateFunctionAsync() method in PuppeteerSharp26EvaluateExpressionAsync() method in PuppeteerSharp27EvaluateHandleFunctionAsync() method in PuppeteerSharp28EvaluateHandleExpressionAsync() method in PuppeteerSharp
AddTagOptions
Using AI Code Generation
1using PuppeteerSharp;2{3 {4 static void Main(string[] args)5 {6 MainAsync().Wait();7 }8 static async Task MainAsync()9 {10 var options = new LaunchOptions { ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" };11 options.AddArgument("--user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data");12 options.AddArgument("--disk-cache-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Cache");13 options.AddArgument("--cookie-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Cookies");14 options.AddArgument("--load-extension=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions");15 options.AddArgument("--bookmark-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks");16 options.AddArgument("--history-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History");17 options.AddArgument("--settings-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Preferences");18 options.AddArgument("--download-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History");19 options.AddArgument("--download-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History");20 options.AddArgument("--download-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History");21 options.AddArgument("--download-store-path=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History");22 options.AddArgument("--download-store-path=C:\\
AddTagOptions
Using AI Code Generation
1using PuppeteerSharp;2using System.Threading.Tasks;3using System;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 {13 };14 using (var browser = await Puppeteer.LaunchAsync(options))15 using (var page = await browser.NewPageAsync())16 {17 await page.ScreenshotAsync("google.png");18 }19 }20 }21}22using PuppeteerSharp;23using System.Threading.Tasks;24using System;25{26 {27 static void Main(string[] args)28 {29 MainAsync().Wait();30 }31 static async Task MainAsync()32 {33 {34 };35 using (var browser = await Puppeteer.LaunchAsync(options))36 using (var page = await browser.NewPageAsync())37 {38 await page.ScreenshotAsync("google.png");39 }40 }41 }42}43using PuppeteerSharp;44using System.Threading.Tasks;45using System;46{47 {48 static void Main(string[] args)49 {50 MainAsync().Wait();51 }52 static async Task MainAsync()53 {54 {55 };56 using (var browser = await Puppeteer.LaunchAsync(options))57 using (var page = await browser.NewPageAsync())58 {59 await page.ScreenshotAsync("google.png");60 }61 }62 }63}64using PuppeteerSharp;65using System.Threading.Tasks;66using System;67{68 {
AddTagOptions
Using AI Code Generation
1{2 {3 }4};5await page.AddScriptTagAsync(options);6{7 Content = "console.log('hello world')"8};9await page.AddScriptTagAsync(options);10{11};12await page.AddScriptTagAsync(options);13{14};15await page.AddScriptTagAsync(options);16{17};18await page.AddScriptTagAsync(options);19{20};21await page.AddScriptTagAsync(options);22{23};24await page.AddScriptTagAsync(options);25{26};27await page.AddScriptTagAsync(options);
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!