Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.AddScriptTag
Page.cs
Source: Page.cs
...424 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content425 /// </summary>426 /// <param name="options">add script tag options</param>427 /// <remarks>428 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(options)</c>429 /// </remarks>430 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>431 /// <seealso cref="Frame.AddScriptTag(AddTagOptions)"/>432 public Task<ElementHandle> AddScriptTagAsync(AddTagOptions options) => MainFrame.AddScriptTag(options);433 /// <summary>434 /// Adds a <c><![CDATA[<script>]]></c> tag into the page with the desired url or content435 /// </summary>436 /// <param name="url">script url</param>437 /// <remarks>438 /// Shortcut for <c>page.MainFrame.AddScriptTagAsync(new AddTagOptions { Url = url })</c>439 /// </remarks>440 /// <returns>Task which resolves to the added tag when the script's onload fires or when the script content was injected into frame</returns>441 public Task<ElementHandle> AddScriptTagAsync(string url) => AddScriptTagAsync(new AddTagOptions { Url = url });442 /// <summary>443 /// 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 content444 /// </summary>445 /// <param name="options">add style tag options</param>446 /// <remarks>447 /// Shortcut for <c>page.MainFrame.AddStyleTagAsync(options)</c>448 /// </remarks>449 /// <returns>Task which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame</returns>450 /// <seealso cref="Frame.AddStyleTag(AddTagOptions)"/>451 public Task<ElementHandle> AddStyleTagAsync(AddTagOptions options) => MainFrame.AddStyleTag(options);452 /// <summary>453 /// 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 content454 /// </summary>455 /// <param name="url">stylesheel url</param>...
Frame.cs
Source: Frame.cs
...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();362 /// <summary>363 /// Sets the HTML markup to the page364 /// </summary>365 /// <param name="html">HTML markup to assign to the page.</param>366 /// <param name="options">The options</param>367 /// <returns>Task.</returns>368 /// <seealso cref="Page.SetContentAsync(string, NavigationOptions)"/>369 public Task SetContentAsync(string html, NavigationOptions options = null)...
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}...
AddScriptTag
Using AI Code Generation
1using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3}))4{5 var page = await browser.NewPageAsync();6 var result = await page.EvaluateExpressionAsync<string>("$('title').text()");7 Console.WriteLine(result);8}
AddScriptTag
Using AI Code Generation
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.WaitForSelectorAsync("input[name='q']");14 await page.TypeAsync("input[name='q']", "PuppeteerSharp");15 await page.Keyboard.PressAsync("Enter");16 await page.WaitForSelectorAsync("h3");17 var h3 = await page.QuerySelectorAsync("h3");18 var text = await page.EvaluateFunctionAsync<string>("h => h.innerText", h3);19 Console.WriteLine(text);20 await browser.CloseAsync();21 }22 }23}
AddScriptTag
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 }10 public 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 AddTagOptions { Content = "console.log('Hello, world!')" });18 await page.EvaluateExpressionAsync("console.log('Hello, world!')");19 }20 }21 }22}
AddScriptTag
Using AI Code Generation
1var frame = (await page.FramesAsync()).FirstOrDefault();2var frame = (await page.FramesAsync()).FirstOrDefault();3var frame = (await page.FramesAsync()).FirstOrDefault();4await frame.AddScriptTagAsync(new AddTagOptions { Path = "jquery.js" });5await page.AddScriptTagAsync(new AddTagOptions { Path = "jquery.js" });6var frame = (await page.FramesAsync()).FirstOrDefault();7await frame.AddScriptTagAsync(new AddTagOptions { Path = "jquery.js" });8await page.AddScriptTagAsync(new AddTagOptions { Path = "jquery.js" });9var frame = (await page.FramesAsync()).FirstOrDefault();10await frame.AddScriptTagAsync(new AddTagOptions { Content = "console.log('Hello World');" });11await page.AddScriptTagAsync(new AddTagOptions { Content = "console.log('Hello World');" });12var frame = (await page.FramesAsync()).FirstOrDefault();13await frame.AddScriptTagAsync(new AddTagOptions { Content = "console.log('Hello World');" });
AddScriptTag
Using AI Code Generation
1var page = await browser.NewPageAsync();2var scriptContent = "console.log('Hello World');";3await page.AddScriptTagAsync(new {content = scriptContent});4var page = await browser.NewPageAsync();5var scriptPath = "C:\\Users\\user\\Desktop\\script.js";6await page.AddScriptTagAsync(new {path = scriptPath});7var page = await browser.NewPageAsync();8var styleContent = "body {background-color: red;}";9await page.AddStyleTagAsync(new {content = styleContent});10var page = await browser.NewPageAsync();11var stylePath = "C:\\Users\\user\\Desktop\\style.css";12await page.AddStyleTagAsync(new {path = stylePath});13var browser = await Puppeteer.LaunchAsync(new LaunchOptions14{15});16var page = await browser.NewPageAsync();17await page.AttachAsync();18var browser = await Puppeteer.LaunchAsync(new LaunchOptions19{20});21var page = await browser.NewPageAsync();22await page.BringToFrontAsync();23var browser = await Puppeteer.LaunchAsync(new LaunchOptions24{25});26var page = await browser.NewPageAsync();27await page.BringToFrontAsync();
AddScriptTag
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.AddScriptTagAsync(new AddTagOptions13 {14 });15 await Task.Delay(5000);16 await browser.CloseAsync();17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 var browser = await Puppeteer.LaunchAsync(new LaunchOptions28 {29 });30 var page = await browser.NewPageAsync();
Puppeteer Sharp strange behaviour
How to get Puppeteer-Sharp working on an AWS Elastic Beanstalk running Docker (.NET Core 6)?
How to implement plugin stealth in Puppeteer Sharp?
Can I use the ScreenshotAsync method to save the screenshot to memory instead of disk?
Cannot click on a button which have a specific attribute
Convert HTML to PDF in .NET
Disposing a Page causes a warning. Is this an issue?
PuppeteerSharp evaluate expression to complex type?
i am getting exception navigation failed because browser has disconnected
Why Puppeteer not working in Brave™ portable?
I found a solution:
If the pages will be created in the same scope as their browser instance, then the pages will be created as expected, otherwise Task.Run()
will be stuck due to NewPageAsync()
method.
Bad behaviour:
Task[] Tasks = new Task[1];
Browser browser = await Puppeteer.LaunchAsync
(
new LaunchOptions
{
Headless = true,
ExecutablePath = "Chromium\\chrome.exe"
}
);
for (int i = 0; i < Tasks.Length; i++)
{
int ThreadNumber = i;
Tasks[i] = Task.Run(async () =>
{
Page page = await browser.NewPageAsync(); //stucks
});
}
Task.WaitAll(Tasks);
As expected:
Task[] Tasks = new Task[1];
for (int i = 0; i < Tasks.Length; i++)
{
int ThreadNumber = i;
Tasks[i] = Task.Run(async () =>
{
Browser browser = await Puppeteer.LaunchAsync
(
new LaunchOptions
{
Headless = true,
ExecutablePath = "Chromium\\chrome.exe"
}
);
Page page = await browser.NewPageAsync(); //creates as expected
});
}
Task.WaitAll(Tasks);
Anyway this is not the best solution because I have to create browsers for async tasks rather than using one browser for all async tasks. Hope someone can explain that. Thanks everyone for helping!
Check out the latest blogs from LambdaTest on this topic:
I was once asked at a testing summit, “How do you manage a QA team using scrum?” After some consideration, I realized it would make a good article, so here I am. Understand that the idea behind developing software in a scrum environment is for development teams to self-organize.
In today’s world, an organization’s most valuable resource is its customers. However, acquiring new customers in an increasingly competitive marketplace can be challenging while maintaining a strong bond with existing clients. Implementing a customer relationship management (CRM) system will allow your organization to keep track of important customer information. This will enable you to market your services and products to these customers better.
Estimates are critical if you want to be successful with projects. If you begin with a bad estimating approach, the project will almost certainly fail. To produce a much more promising estimate, direct each estimation-process issue toward a repeatable standard process. A smart approach reduces the degree of uncertainty. When dealing with presales phases, having the most precise estimation findings can assist you to deal with the project plan. This also helps the process to function more successfully, especially when faced with tight schedules and the danger of deviation.
It’s strange to hear someone declare, “This can’t be tested.” In reply, I contend that everything can be tested. However, one must be pleased with the outcome of testing, which might include failure, financial loss, or personal injury. Could anything be tested when a claim is made with this understanding?
So, now that the first installment of this two fold article has been published (hence you might have an idea of what Agile Testing is not in my opinion), I’ve started feeling the pressure to explain what Agile Testing actually means to me.
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!!