How to use AddStyleTagAsync method of PuppeteerSharp.Page class

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

Frame.cs

Source:Frame.cs Github

copy

Full Screen

...323 /// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content324 /// </summary>325 /// <param name="options">add style tag options</param>326 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>327 /// <seealso cref="Page.AddStyleTagAsync(AddTagOptions)"/>328 /// <seealso cref="Page.AddStyleTagAsync(string)"/>329 [Obsolete("Use AddStyleTagAsync instead")]330 public Task<ElementHandle> AddStyleTag(AddTagOptions options) => MainWorld.AddStyleTagAsync(options);331 /// <summary>332 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content333 /// </summary>334 /// <param name="options">add script tag options</param>335 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>336 /// <seealso cref="Page.AddScriptTagAsync(AddTagOptions)"/>337 /// <seealso cref="Page.AddScriptTagAsync(string)"/>338 [Obsolete("Use AddScriptTagAsync instead")]339 public Task<ElementHandle> AddScriptTag(AddTagOptions options) => MainWorld.AddScriptTagAsync(options);340 /// <summary>341 /// Adds a <c><![CDATA[<link rel="stylesheet">]]></c> tag into the page with the desired url or a <c><![CDATA[<link rel="stylesheet">]]></c> tag with the content342 /// </summary>343 /// <param name="options">add style tag options</param>344 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>345 /// <seealso cref="Page.AddStyleTagAsync(AddTagOptions)"/>346 /// <seealso cref="Page.AddStyleTagAsync(string)"/>347 public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainWorld.AddStyleTagAsync(options);348 /// <summary>349 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content350 /// </summary>351 /// <param name="options">add script tag options</param>352 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>353 /// <seealso cref="Page.AddScriptTagAsync(AddTagOptions)"/>354 /// <seealso cref="Page.AddScriptTagAsync(string)"/>355 public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainWorld.AddScriptTagAsync(options);356 /// <summary>357 /// Gets the full HTML contents of the page, including the doctype.358 /// </summary>359 /// <returns>Task which resolves to the HTML content.</returns>360 /// <seealso cref="Page.GetContentAsync"/>361 public Task<string> GetContentAsync() => SecondaryWorld.GetContentAsync();...

Full Screen

Full Screen

CSSCoverageTests.cs

Source:CSSCoverageTests.cs Github

copy

Full Screen

...111 [Fact]112 public async Task ShouldIgnoreInjectedStylesheets()113 {114 await Page.Coverage.StartCSSCoverageAsync();115 await Page.AddStyleTagAsync(new AddTagOptions116 {117 Content = "body { margin: 10px;}"118 });119 // trigger style recalc120 var margin = await Page.EvaluateExpressionAsync<string>("window.getComputedStyle(document.body).margin");121 Assert.Equal("10px", margin);122 var coverage = await Page.Coverage.StopCSSCoverageAsync();123 Assert.Empty(coverage);124 }125 }126}...

Full Screen

Full Screen

DocumentsController.cs

Source:DocumentsController.cs Github

copy

Full Screen

...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 }...

Full Screen

Full Screen

PuppeteerPdfGenerator.cs

Source:PuppeteerPdfGenerator.cs Github

copy

Full Screen

...89 if (request.Options?.AddStyleTags is {Count : > 0})90 {91 foreach (var tag in request.Options.AddStyleTags)92 {93 await page.AddStyleTagAsync(tag);94 }95 }96 }97 private static string InjectLoaderScript(string html)98 {99 const string script = "<script>window.onload = function() { window.IsPageLoaded= true; };</script>";100 if (html.Contains("</body>"))101 return html.Replace("</body>",102 $"{script}</body>");103 return html + script;104 }105 }106}...

Full Screen

Full Screen

AddStyleTagTests.cs

Source:AddStyleTagTests.cs Github

copy

Full Screen

...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}

Full Screen

Full Screen

ImageHelper.cs

Source:ImageHelper.cs Github

copy

Full Screen

...22 width: calc({(pdfOptions.Landscape ? height : width)} - {pdfOptions.MarginOptions.Left} - {pdfOptions.MarginOptions.Right});23 height: calc({(pdfOptions.Landscape ? width : height)} - {pdfOptions.MarginOptions.Top} - {pdfOptions.MarginOptions.Bottom});24 }}25 ";26 await page.AddStyleTagAsync(new AddTagOptions { Content = cssContent });27 }28 public static async Task<bool> IsLandscapeAsync(Page page)29 {30 var script = @"31 () => {32 const image = document.querySelector('img');33 return [image.clientWidth, image.clientHeight];34 }35 ";36 var size = await page.EvaluateFunctionAsync<int[]>(script);37 return size[0] > size[1];38 }39 }40}...

Full Screen

Full Screen

HtmlToPdfBL.cs

Source:HtmlToPdfBL.cs Github

copy

Full Screen

...20 Headless = true21 });22 var page = await browser.NewPageAsync();23 await page.SetContentAsync(html);24 await page.AddStyleTagAsync(new AddTagOptions { Path = cssPath });25 var stream = await page.PdfStreamAsync(pdfOptions);26 using var ms = new MemoryStream();27 await stream.CopyToAsync(ms);28 return ms.ToArray();29 }30 }31}...

Full Screen

Full Screen

AddTagOptions.cs

Source:AddTagOptions.cs Github

copy

Full Screen

1namespace PuppeteerSharp2{3 /// <summary>4 /// Options used by <see cref="Page.AddScriptTagAsync(AddTagOptions)"/> &amp; <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>...

Full Screen

Full Screen

AddStyleTagAsync

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 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.AddStyleTagAsync(new AddTagOptions { Content = "body { background-color: green; }" });16 }

Full Screen

Full Screen

AddStyleTagAsync

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 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 await page.AddStyleTagAsync(new AddTagOptions { Path = "C:\\Users\\Public\\Documents\\style.css" });12 await page.AddStyleTagAsync(new AddTagOptions { Content = "body { background-color: green; }" });13 await page.ScreenshotAsync("screenshot.png");14 await browser.CloseAsync();15 }16 }17}

Full Screen

Full Screen

AddStyleTagAsync

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 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);13 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))14 {15 using (var page = await browser.NewPageAsync())16 {17 await page.GoToAsync(url);18 Console.WriteLine("Press any key to exit");19 Console.ReadKey();20 }21 }22 }23 }24}

Full Screen

Full Screen

AddStyleTagAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();7 static async Task MainAsync()8 {9 {10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.AddStyleTagAsync(new AddTagOptions16 {17 });18 await page.AddStyleTagAsync(new AddTagOptions19 {20 Content = "body { background-color: red; }"21 });22 await page.AddStyleTagAsync(new AddTagOptions23 {24 });25 await page.AddStyleTagAsync(new AddTagOptions26 {27 });28 await page.AddStyleTagAsync(new AddTagOptions29 {30 });31 }32 }33 }34 }35}36C# VB C++ F# Copy Task AddStyleTagAsync ( AddTagOptions options ) Task AddStyleTagAsync ( AddTagOptions options ) Task < AddTagResult > AddStyleTagAsync ( AddTagOptions options ) Task < AddTagResult > AddStyleTagAsync ( AddTagOptions options ) Parameters options Type: PuppeteerSharp.AddTagOptions

Full Screen

Full Screen

AddStyleTagAsync

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 options = new LaunchOptions { Headless = true };13 using (var browser = await Puppeteer.LaunchAsync(options))14 using (var page = await browser.NewPageAsync())15 {16 await page.AddStyleTagAsync(new AddTagOptions17 {18 });19 }20 }21 }22}23using PuppeteerSharp;24using System;25using System.Threading.Tasks;26{27 {28 static void Main(string[] args)29 {30 MainAsync().Wait();31 }32 static async Task MainAsync()33 {34 var options = new LaunchOptions { Headless = true };35 using (var browser = await Puppeteer.LaunchAsync(options))36 using (var page = await browser.NewPageAsync())37 {38 await page.AddStyleTagAsync(new AddTagOptions39 {40 Content = "body {background-color: #000000;}"41 });42 }43 }44 }45}

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