How to use SetBypassCSPAsync method of PuppeteerSharp.Page class

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

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

PuppeteerController.cs

Source: PuppeteerController.cs Github

copy
1using System;
2using System.IO;
3using System.Threading.Tasks;
4using PuppeteerSharp;
5using PuppeteerSharpController.Strategies;
6
7namespace PuppeteerSharpController
8{
9    public class PuppeteerController
10    {
11        /// <summary>
12        /// Creates a controller/interface for controlling Puppeteer.
13        /// </summary>
14        public PuppeteerController() { }
15
16        /// <summary>
17        /// Generates the result based on the component name, located at \Components\, the data and the return strategy.
18        /// </summary>
19        /// <param name="componentName">\Components\$componentName\index.html</param>
20        /// <param name="mydata">the data</param>
21        /// <param name="strategy">from PuppeteerSharpController.Strategies.Download</param>
22        /// <returns>returns the response as a string</returns>
23        public async Task<string> GenerateContent(string componentName, string mydata, IStrategy strategy)
24        {
25            if (string.IsNullOrEmpty(componentName) || string.IsNullOrEmpty(mydata) || strategy == null)
26                return "Invalid request";
27
28            // Create the Browser context
29            using Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
30            {
31                Headless = true,    // No UI. If you want to debug, change it to false.
32                ExecutablePath = PuppeteerInstaller.CHROMIUM_EXECUTION_PATH,
33                IgnoreHTTPSErrors = true,   // ONLY if you're using internal resources only.
34                Timeout = (int)TimeSpan.FromMinutes(3).TotalMilliseconds,
35                UserDataDir = PuppeteerInstaller.CHROMIUM_TEMP_DATA_DIR 
36                // The PuppeteerSharp Data Directory, 
37                // if you don't specify it, PuppeteerSharp will create TEMP folders for each session 
38                // at a system \Temp folder, which can exceed the system space
39            });
40
41            // Create the page context
42            using Page page = await browser.NewPageAsync();
43            Console.WriteLine($"Opening page: {page.Url}");
44
45            await page.SetJavaScriptEnabledAsync(true);
46            await page.SetBypassCSPAsync(true);
47
48            // Sets the data as a DOM variable
49            await page.EvaluateExpressionAsync($"var mydata = '{mydata}'");
50
51            // Sets the path of the component's entry point
52            string sourceIndexPath = $"{Environment.CurrentDirectory}/Components/{componentName}/index.html";
53            await page.SetContentAsync(ReadFile(sourceIndexPath));
54
55            // Sets the strategy page to be the current Puppeteer Page
56            strategy.PuppeteerPage = page;
57
58            // Executes the strategy
59            return await strategy.Execute();
60        }
61
62        /// <summary>
63        /// Installs Puppeteer
64        /// </summary>
65        public static async Task InstallPuppeteer()
66        {
67            PuppeteerInstaller puppeteerInstaller = new PuppeteerInstaller();
68            await puppeteerInstaller.DownloadAndInstall();
69        }
70
71        /// <summary>
72        /// Reads the content of a file
73        /// </summary>
74        private string ReadFile(string filepath)
75        {
76            try
77            {
78                return File.ReadAllText(filepath);
79            }
80            catch (AggregateException ex)
81            {
82                Console.WriteLine($"Error while reading the HTML file: {ex.Message}.");
83                return string.Empty;
84            }
85        }
86
87    }
88}
89
Full Screen

RecapchaPlugin.cs

Source: RecapchaPlugin.cs Github

copy
1using System.Threading.Tasks;
2using PuppeteerExtraSharp.Plugins.Recaptcha.Provider;
3using PuppeteerSharp;
4
5namespace PuppeteerExtraSharp.Plugins.Recaptcha
6{
7    public class RecaptchaPlugin : PuppeteerExtraPlugin
8    {
9        private readonly Recaptcha _recaptcha;
10
11        public RecaptchaPlugin(IRecaptchaProvider provider, CaptchaOptions opt = null) : base("recaptcha")
12        {
13            _recaptcha = new Recaptcha(provider, opt ?? new CaptchaOptions());
14        }
15
16        public async Task<RecaptchaResult> SolveCaptchaAsync(Page page)
17        {
18            return await _recaptcha.Solve(page);
19        }
20
21        public override async Task OnPageCreated(Page page)
22        {
23            await page.SetBypassCSPAsync(true);
24        }
25    }
26}
27
Full Screen

SetBypassCSPTests.cs

Source: SetBypassCSPTests.cs Github

copy
1using System.Threading.Tasks;
2using PuppeteerSharp.Tests.Attributes;
3using PuppeteerSharp.Xunit;
4using Xunit;
5using Xunit.Abstractions;
6
7namespace PuppeteerSharp.Tests.PageTests
8{
9    [Collection(TestConstants.TestFixtureCollectionName)]
10    public class SetBypassCSPTests : PuppeteerPageBaseTest
11    {
12        public SetBypassCSPTests(ITestOutputHelper output) : base(output)
13        {
14        }
15
16        [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass CSP meta tag")]
17        [SkipBrowserFact(skipFirefox: true)]
18        public async Task ShouldBypassCSPMetaTag()
19        {
20            // Make sure CSP prohibits addScriptTag.
21            await Page.GoToAsync(TestConstants.ServerUrl + "/csp.html");
22            await Page.AddScriptTagAsync(new AddTagOptions
23            {
24                Content = "window.__injected = 42;"
25            }).ContinueWith(_ => Task.CompletedTask);
26            Assert.Null(await Page.EvaluateExpressionAsync("window.__injected"));
27
28            // By-pass CSP and try one more time.
29            await Page.SetBypassCSPAsync(true);
30            await Page.ReloadAsync();
31            await Page.AddScriptTagAsync(new AddTagOptions
32            {
33                Content = "window.__injected = 42;"
34            });
35            Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));
36        }
37
38        [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass CSP header")]
39        [SkipBrowserFact(skipFirefox: true)]
40        public async Task ShouldBypassCSPHeader()
41        {
42            // Make sure CSP prohibits addScriptTag.
43            Server.SetCSP("/empty.html", "default-src 'self'");
44            await Page.GoToAsync(TestConstants.EmptyPage);
45            await Page.AddScriptTagAsync(new AddTagOptions
46            {
47                Content = "window.__injected = 42;"
48            }).ContinueWith(_ => Task.CompletedTask);
49            Assert.Null(await Page.EvaluateExpressionAsync("window.__injected"));
50
51            // By-pass CSP and try one more time.
52            await Page.SetBypassCSPAsync(true);
53            await Page.ReloadAsync();
54            await Page.AddScriptTagAsync(new AddTagOptions
55            {
56                Content = "window.__injected = 42;"
57            });
58            Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));
59        }
60
61        [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass after cross-process navigation")]
62        [SkipBrowserFact(skipFirefox: true)]
63        public async Task ShouldBypassAfterCrossProcessNavigation()
64        {
65            await Page.SetBypassCSPAsync(true);
66            await Page.GoToAsync(TestConstants.ServerUrl + "/csp.html");
67            await Page.AddScriptTagAsync(new AddTagOptions
68            {
69                Content = "window.__injected = 42;"
70            });
71            Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));
72
73            await Page.GoToAsync(TestConstants.CrossProcessUrl + "/csp.html");
74            await Page.AddScriptTagAsync(new AddTagOptions
75            {
76                Content = "window.__injected = 42;"
77            });
78            Assert.Equal(42, await Page.EvaluateExpressionAsync<int>("window.__injected"));
79        }
80
81        [PuppeteerTest("page.spec.ts", "Page.setBypassCSP", "should bypass CSP in iframes as well")]
82        [SkipBrowserFact(skipFirefox: true)]
83        public async Task ShouldBypassCSPInIframesAsWell()
84        {
85            await Page.GoToAsync(TestConstants.EmptyPage);
86
87            // Make sure CSP prohibits addScriptTag in an iframe.
88            var frame = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.ServerUrl + "/csp.html");
89            await frame.AddScriptTagAsync(new AddTagOptions
90            {
91                Content = "window.__injected = 42;"
92            }).ContinueWith(_ => Task.CompletedTask);
93            Assert.Null(await frame.EvaluateFunctionAsync<int?>("() => window.__injected"));
94
95            // By-pass CSP and try one more time.
96            await Page.SetBypassCSPAsync(true);
97            await Page.ReloadAsync();
98
99            // Make sure CSP prohibits addScriptTag in an iframe.
100            frame = await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.ServerUrl + "/csp.html");
101            await frame.AddScriptTagAsync(new AddTagOptions
102            {
103                Content = "window.__injected = 42;"
104            }).ContinueWith(_ => Task.CompletedTask);
105            Assert.Equal(42, await frame.EvaluateFunctionAsync<int?>("() => window.__injected"));
106        }
107    }
108}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in Page

Trigger SetBypassCSPAsync code on LambdaTest Cloud Grid

Execute automation tests with SetBypassCSPAsync on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)