├── .gitattributes
├── .gitignore
├── BrowserStartContext.cs
├── Helpers
├── EnumHelpers.cs
├── OptionsHelpers.cs
└── PageHelpers.cs
├── LICENSE.txt
├── Models
├── BrowserTypeEnum.cs
├── OverrideUserAgent.cs
├── PluginData.cs
├── PluginRequirement.cs
├── PluginType.cs
├── UserAgentBrand.cs
└── UserAgentMetadata.cs
├── PlaywrightExtra.cs
├── PlaywrightExtraSharp.csproj
├── PlaywrightExtraSharp.sln
├── Plugins
├── AnonymizeUa
│ └── AnonymizeUaExtraPlugin.cs
├── BlockResources
│ ├── BlockResourcesExtraPlugin.cs
│ └── BlockRule.cs
├── DisposeContext.cs
├── ExtraStealth
│ ├── Evasions
│ │ ├── ChromeApp.cs
│ │ ├── ChromeRuntime.cs
│ │ ├── ChromeSci.cs
│ │ ├── Codec.cs
│ │ ├── ContentWindow.cs
│ │ ├── ExtraPluginEvasion.cs
│ │ ├── HardwareConcurrency.cs
│ │ ├── Languages.cs
│ │ ├── LoadTimes.cs
│ │ ├── OutDimensions.cs
│ │ ├── Permissions.cs
│ │ ├── SourceUrl.cs
│ │ ├── StackTrace.cs
│ │ ├── UserAgent.cs
│ │ ├── Vendor.cs
│ │ ├── WebDriver.cs
│ │ └── WebGl.cs
│ └── StealthExtraPlugin.cs
├── IPuppeteerExtraPluginOptions.cs
├── PlaywrightExtraPlugin.cs
├── Recaptcha
│ ├── CaptchaCfg.cs
│ ├── CaptchaException.cs
│ ├── CaptchaOptions.cs
│ ├── Provider
│ │ ├── 2Captcha
│ │ │ ├── Models
│ │ │ │ ├── TwoCaptchaRequest.cs
│ │ │ │ └── TwoCaptchaResponse.cs
│ │ │ ├── TwoCaptcha.cs
│ │ │ └── TwoCaptchaApi.cs
│ │ ├── AntiCaptcha
│ │ │ ├── AntiCaptcha.cs
│ │ │ ├── AntiCaptchaApi.cs
│ │ │ └── Models
│ │ │ │ ├── AntiCaptchaRequest.cs
│ │ │ │ └── TaskResultModel.cs
│ │ ├── IRecaptchaProvider.cs
│ │ └── ProviderOptions.cs
│ ├── RecapchaPlugin.cs
│ ├── Recaptcha.cs
│ ├── RecaptchaResult.cs
│ ├── RestClient
│ │ ├── PollingBuilder.cs
│ │ └── RestClient.cs
│ └── Scripts
│ │ └── EnterRecaptchaCallBackScript.js
└── Scripts
│ ├── ChromeApp.js
│ ├── Codec.js
│ ├── ContentWindow.js
│ ├── HardwareConcurrency.js
│ ├── Language.js
│ ├── LoadTimes.js
│ ├── Outdimensions.js
│ ├── Permissions.js
│ ├── Plugin.js
│ ├── Runtime.js
│ ├── SCI.js
│ ├── Stacktrace.js
│ ├── Utils.js
│ ├── Vendor.js
│ ├── WebDriver.js
│ └── WebGL.js
├── README.md
└── Utils
└── ResourceReader.cs
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.js linguist-detectable=false
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
400 | .idea/
--------------------------------------------------------------------------------
/BrowserStartContext.cs:
--------------------------------------------------------------------------------
1 | namespace PlaywrightExtraSharp;
2 |
3 | public class BrowserStartContext
4 | {
5 | public bool IsHeadless { get; set; }
6 | public StartType StartType { get; set; }
7 | }
8 |
9 | public enum StartType
10 | {
11 | Connect,
12 | Launch
13 | }
--------------------------------------------------------------------------------
/Helpers/EnumHelpers.cs:
--------------------------------------------------------------------------------
1 | using PlaywrightExtraSharp.Models;
2 |
3 | namespace PlaywrightExtraSharp.Helpers;
4 |
5 | public static class EnumHelpers
6 | {
7 | public static string GetBrowserName(this BrowserTypeEnum browserTypeEnum)
8 | {
9 | return browserTypeEnum.ToString().ToLowerInvariant();
10 | }
11 | }
--------------------------------------------------------------------------------
/Helpers/OptionsHelpers.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Helpers;
4 |
5 | public static class OptionsHelpers
6 | {
7 | public static BrowserNewContextOptions ToContextOptions(this BrowserNewPageOptions options, BrowserNewContextOptions? contextOptions = null)
8 | {
9 | return new BrowserNewContextOptions(contextOptions)
10 | {
11 | AcceptDownloads = options.AcceptDownloads,
12 | IgnoreHTTPSErrors = options.IgnoreHTTPSErrors,
13 | BypassCSP = options.BypassCSP,
14 | ViewportSize = options.ViewportSize,
15 | ScreenSize = options.ScreenSize,
16 | UserAgent = options.UserAgent,
17 | DeviceScaleFactor = options.DeviceScaleFactor,
18 | IsMobile = options.IsMobile,
19 | HasTouch = options.HasTouch,
20 | JavaScriptEnabled = options.JavaScriptEnabled,
21 | TimezoneId = options.TimezoneId,
22 | Geolocation = options.Geolocation,
23 | Locale = options.Locale,
24 | Permissions = options.Permissions,
25 | ExtraHTTPHeaders = options.ExtraHTTPHeaders,
26 | Offline = options.Offline,
27 | HttpCredentials = options.HttpCredentials,
28 | ColorScheme = options.ColorScheme,
29 | ReducedMotion = options.ReducedMotion,
30 | ForcedColors = options.ForcedColors,
31 | RecordHarPath = options.RecordHarPath,
32 | RecordHarContent = options.RecordHarContent,
33 | RecordHarMode = options.RecordHarMode,
34 | RecordHarOmitContent = options.RecordHarOmitContent,
35 | RecordHarUrlFilter = options.RecordHarUrlFilter,
36 | RecordHarUrlFilterString = options.RecordHarUrlFilterString,
37 | RecordHarUrlFilterRegex = options.RecordHarUrlFilterRegex,
38 | RecordVideoDir = options.RecordVideoDir,
39 | RecordVideoSize = options.RecordVideoSize,
40 | Proxy = options.Proxy,
41 | ServiceWorkers = options.ServiceWorkers,
42 | BaseURL = options.BaseURL,
43 | StrictSelectors = options.StrictSelectors
44 | };
45 | }
46 |
47 | public static BrowserTypeLaunchPersistentContextOptions ToPersistentContextOptions(this BrowserNewPageOptions options, BrowserTypeLaunchPersistentContextOptions? persistentContextOptions)
48 | {
49 | return new BrowserTypeLaunchPersistentContextOptions(persistentContextOptions)
50 | {
51 | AcceptDownloads = options.AcceptDownloads,
52 | IgnoreHTTPSErrors = options.IgnoreHTTPSErrors,
53 | BypassCSP = options.BypassCSP,
54 | ViewportSize = options.ViewportSize,
55 | ScreenSize = options.ScreenSize,
56 | UserAgent = options.UserAgent,
57 | DeviceScaleFactor = options.DeviceScaleFactor,
58 | IsMobile = options.IsMobile,
59 | HasTouch = options.HasTouch,
60 | JavaScriptEnabled = options.JavaScriptEnabled,
61 | TimezoneId = options.TimezoneId,
62 | Geolocation = options.Geolocation,
63 | Locale = options.Locale,
64 | Permissions = options.Permissions,
65 | ExtraHTTPHeaders = options.ExtraHTTPHeaders,
66 | Offline = options.Offline,
67 | HttpCredentials = options.HttpCredentials,
68 | ColorScheme = options.ColorScheme,
69 | ReducedMotion = options.ReducedMotion,
70 | ForcedColors = options.ForcedColors,
71 | RecordHarPath = options.RecordHarPath,
72 | RecordHarContent = options.RecordHarContent,
73 | RecordHarMode = options.RecordHarMode,
74 | RecordHarOmitContent = options.RecordHarOmitContent,
75 | RecordHarUrlFilter = options.RecordHarUrlFilter,
76 | RecordHarUrlFilterString = options.RecordHarUrlFilterString,
77 | RecordHarUrlFilterRegex = options.RecordHarUrlFilterRegex,
78 | RecordVideoDir = options.RecordVideoDir,
79 | RecordVideoSize = options.RecordVideoSize,
80 | Proxy = options.Proxy,
81 | ServiceWorkers = options.ServiceWorkers,
82 | BaseURL = options.BaseURL,
83 | StrictSelectors = options.StrictSelectors
84 | };
85 | }
86 | }
--------------------------------------------------------------------------------
/Helpers/PageHelpers.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Microsoft.Playwright;
3 |
4 | namespace PlaywrightExtraSharp.Helpers;
5 |
6 | public static class PageHelpers
7 | {
8 | ///
9 | /// Requests url and waits before network is idle or number of requests started equals finished
10 | ///
11 | /// Page from Playwright
12 | /// Url to request
13 | /// Page goto options
14 | /// Network idle time before request considered finished
15 | /// Some sites load only one script and after setTimeout loads everything else. This time between page request completed and before any new requests will spawn will be awaited
16 | ///
17 | public static async Task GotoAndWaitForIdleAsync(
18 | this IPage page,
19 | string url,
20 | PageGotoOptions? options = null,
21 | TimeSpan? idleTime = null,
22 | TimeSpan? timeBeforeScriptsActivate = null)
23 | {
24 | idleTime ??= TimeSpan.FromMilliseconds(500);
25 | timeBeforeScriptsActivate ??= TimeSpan.FromMilliseconds(500);
26 |
27 | var requestsStarted = 0;
28 | var requestsFinished = 0;
29 |
30 | var autoResetEvent = new AutoResetEvent(false);
31 |
32 | page.Request += PageOnRequestStarted;
33 | page.RequestFinished += PageOnRequestFinished;
34 | page.RequestFailed += PageOnRequestFinished;
35 |
36 | var retries = 10;
37 | IResponse? response = null;
38 | while (retries-- > 0)
39 | {
40 | try
41 | {
42 | response = await page.GotoAsync(url, options);
43 | await page.WaitForTimeoutAsync((float)timeBeforeScriptsActivate.Value.TotalMilliseconds);
44 | break;
45 | }
46 | catch (PlaywrightException pwe)
47 | {
48 | }
49 | }
50 |
51 | var lastRequestFinishedAt = DateTime.UtcNow;
52 |
53 | while (true)
54 | {
55 | autoResetEvent.WaitOne(100);
56 |
57 | if (requestsStarted == requestsFinished || DateTime.UtcNow - lastRequestFinishedAt >= idleTime)
58 | break;
59 | }
60 |
61 | page.Request -= PageOnRequestStarted;
62 | page.RequestFinished -= PageOnRequestFinished;
63 | page.RequestFailed -= PageOnRequestFinished;
64 |
65 | return response;
66 |
67 | void PageOnRequestStarted(object sender, IRequest request)
68 | {
69 | requestsStarted++;
70 | lastRequestFinishedAt = DateTime.UtcNow;
71 | }
72 |
73 | void PageOnRequestFinished(object sender, IRequest request)
74 | {
75 | requestsFinished++;
76 | lastRequestFinishedAt = DateTime.UtcNow;
77 | autoResetEvent.Set();
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Georgy Kazakov
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Models/BrowserTypeEnum.cs:
--------------------------------------------------------------------------------
1 | namespace PlaywrightExtraSharp.Models;
2 |
3 | public enum BrowserTypeEnum
4 | {
5 | Chromium,
6 | Firefox,
7 | Webkit
8 | }
--------------------------------------------------------------------------------
/Models/OverrideUserAgent.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace PlaywrightExtraSharp.Models;
4 |
5 | internal class OverrideUserAgent
6 | {
7 | public OverrideUserAgent(string userAgent, string platform, string acceptLanguage,
8 | UserAgentMetadata userAgentMetadata)
9 | {
10 | UserAgent = userAgent;
11 | Platform = platform;
12 | AcceptLanguage = acceptLanguage;
13 | UserAgentMetadata = userAgentMetadata;
14 | }
15 |
16 | [JsonPropertyName("userAgent")] public string UserAgent { get; }
17 | [JsonPropertyName("platform")] public string Platform { get; }
18 | [JsonPropertyName("acceptLanguage")] public string AcceptLanguage { get; }
19 |
20 | [JsonPropertyName("userAgentMetadata")]
21 | public UserAgentMetadata UserAgentMetadata { get; }
22 | }
--------------------------------------------------------------------------------
/Models/PluginData.cs:
--------------------------------------------------------------------------------
1 | namespace PlaywrightExtraSharp.Models;
2 |
3 | public sealed class PluginData
4 | {
5 | public PluginData(string name, string value)
6 | {
7 | Name = name;
8 | Value = value;
9 | }
10 |
11 | public string Name { get; }
12 | public string Value { get; }
13 | }
--------------------------------------------------------------------------------
/Models/PluginRequirement.cs:
--------------------------------------------------------------------------------
1 | namespace PlaywrightExtraSharp.Models;
2 |
3 | public enum PluginRequirement
4 | {
5 | Launch,
6 | Headful,
7 | DataFromPlugins,
8 | RunLast
9 | }
--------------------------------------------------------------------------------
/Models/PluginType.cs:
--------------------------------------------------------------------------------
1 | namespace PlaywrightExtraSharp.Models;
2 |
3 | public enum PluginType
4 | {
5 | Stealth
6 | }
--------------------------------------------------------------------------------
/Models/UserAgentBrand.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace PlaywrightExtraSharp.Models;
4 |
5 | internal class UserAgentBrand
6 | {
7 | public UserAgentBrand(string brand, string version)
8 | {
9 | Brand = brand;
10 | Version = version;
11 | }
12 |
13 | [JsonPropertyName("brand")] public string Brand { get; }
14 | [JsonPropertyName("version")] public string Version { get; }
15 | }
--------------------------------------------------------------------------------
/Models/UserAgentMetadata.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace PlaywrightExtraSharp.Models;
4 |
5 | internal class UserAgentMetadata
6 | {
7 | public UserAgentMetadata(List brands, string fullVersion, string platform,
8 | string platformVersion, string architecture, string model, bool mobile)
9 | {
10 | Brands = brands;
11 | FullVersion = fullVersion;
12 | Platform = platform;
13 | PlatformVersion = platformVersion;
14 | Architecture = architecture;
15 | Model = model;
16 | Mobile = mobile;
17 | }
18 |
19 | [JsonPropertyName("brands")] public List Brands { get; }
20 | [JsonPropertyName("fullVersion")] public string FullVersion { get; }
21 | [JsonPropertyName("platform")] public string Platform { get; }
22 | [JsonPropertyName("platformVersion")] public string PlatformVersion { get; }
23 | [JsonPropertyName("architecture")] public string Architecture { get; }
24 | [JsonPropertyName("model")] public string Model { get; }
25 | [JsonPropertyName("mobile")] public bool Mobile { get; }
26 | }
--------------------------------------------------------------------------------
/PlaywrightExtra.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 | using PlaywrightExtraSharp.Helpers;
3 | using PlaywrightExtraSharp.Models;
4 | using PlaywrightExtraSharp.Plugins;
5 |
6 | namespace PlaywrightExtraSharp;
7 |
8 | public class PlaywrightExtra : IBrowser, IDisposable
9 | {
10 | private readonly BrowserTypeEnum _browserTypeEnum;
11 | private IBrowser? _browser;
12 | private IBrowserContext? _browserContext;
13 | private IPlaywright? _playwright;
14 | private List _plugins = new();
15 | private bool _persistContext;
16 | private bool _persistentLaunch;
17 | private string? _userDataDir;
18 | private BrowserNewContextOptions? _contextOptions;
19 | private BrowserTypeLaunchPersistentContextOptions? _persistentContextOptions;
20 |
21 | public PlaywrightExtra(BrowserTypeEnum browserTypeEnum)
22 | {
23 | _browserTypeEnum = browserTypeEnum;
24 |
25 | //Use(new DisposeContext());
26 | }
27 |
28 | public PlaywrightExtra Use(PlaywrightExtraPlugin extraPlugin)
29 | {
30 | _plugins.Add(extraPlugin);
31 | ResolveDependencies(extraPlugin);
32 | extraPlugin.OnPluginRegistered();
33 |
34 | return this;
35 | }
36 |
37 | public PlaywrightExtra Install()
38 | {
39 | var exitCode = Program.Main(new[] { "install", "--with-deps", _browserTypeEnum.GetBrowserName() });
40 | if (exitCode != 0) throw new Exception($"Playwright exited with code {exitCode}");
41 |
42 | return this;
43 | }
44 |
45 | public async Task LaunchPersistentAsync(BrowserTypeLaunchPersistentContextOptions? options = null, bool persistContext = true, string? userDataDir = null)
46 | {
47 | _persistContext = persistContext;
48 | _persistentLaunch = true;
49 | _userDataDir = userDataDir;
50 | _persistentContextOptions = options ?? new BrowserTypeLaunchPersistentContextOptions();
51 |
52 | _playwright = await Playwright.CreateAsync();
53 |
54 | await TriggerEventAndWait(x => x.BeforeLaunch(null, options));
55 |
56 | if (_persistContext)
57 | {
58 | await TriggerEventAndWait(x => x.BeforeContext(null, options));
59 | _browserContext = await _playwright[_browserTypeEnum.GetBrowserName()]
60 | .LaunchPersistentContextAsync(userDataDir ?? "", options);
61 |
62 | await TriggerEventAndWait(x => x.OnContextCreated(_browserContext, null, options));
63 |
64 | _browser = _browserContext.Browser;
65 |
66 | await TriggerEventAndWait(x => x.OnBrowser(_browser, null));
67 |
68 | _browserContext.Close += async (_, targetBrowserContext) =>
69 | await TriggerEventAndWait(x => x.OnDisconnected(null, targetBrowserContext));
70 |
71 | await TriggerEventAndWait(x => x.AfterLaunch(_browser));
72 | }
73 |
74 | OrderPlugins();
75 | CheckPluginRequirements(new BrowserStartContext
76 | {
77 | StartType = StartType.Launch,
78 | IsHeadless = options?.Headless ?? false
79 | });
80 |
81 | return this;
82 | }
83 |
84 | public async Task LaunchAsync(BrowserTypeLaunchOptions? options = null, bool persistContext = true, BrowserNewContextOptions? contextOptions = null)
85 | {
86 | _persistContext = persistContext;
87 | _persistentLaunch = false;
88 | _contextOptions = contextOptions ?? new BrowserNewContextOptions();
89 |
90 | await TriggerEventAndWait(x => x.BeforeLaunch(options, null));
91 |
92 | _playwright = await Playwright.CreateAsync();
93 | _browser = await _playwright[_browserTypeEnum.GetBrowserName()].LaunchAsync(options);
94 | await TriggerEventAndWait(x => x.OnBrowser(_browser, null));
95 |
96 | _browser.Disconnected += async (_, targetBrowser) =>
97 | await TriggerEventAndWait(x => x.OnDisconnected(_browser, null));
98 |
99 | if (_persistContext)
100 | {
101 | await TriggerEventAndWait(x => x.BeforeContext(contextOptions, null));
102 | _browserContext = await _browser.NewContextAsync(contextOptions);
103 | await TriggerEventAndWait(x => x.OnContextCreated(_browserContext, contextOptions, null));
104 |
105 | _browserContext.Close += async (_, context) =>
106 | await TriggerEventAndWait(x => x.OnDisconnected(null, context));
107 |
108 | var blankPage = await _browserContext.NewPageAsync();
109 | await blankPage.GotoAsync("about:blank");
110 | }
111 |
112 | await TriggerEventAndWait(x => x.AfterLaunch(_browser));
113 |
114 | OrderPlugins();
115 | CheckPluginRequirements(new BrowserStartContext
116 | {
117 | StartType = StartType.Launch,
118 | IsHeadless = options?.Headless ?? false
119 | });
120 |
121 | return this;
122 | }
123 |
124 | public async Task ConnectAsync(string wsEndpoint, BrowserTypeConnectOptions? options = null)
125 | {
126 | _persistContext = true;
127 | _persistentLaunch = false;
128 |
129 | await TriggerEventAndWait(x => x.BeforeConnect(options));
130 |
131 | _playwright = await Playwright.CreateAsync();
132 | _browser = (await _playwright[_browserTypeEnum.GetBrowserName()].ConnectAsync(wsEndpoint, options));
133 | _browserContext = _browser.Contexts.First();
134 |
135 | await TriggerEventAndWait(x => x.AfterConnect(_browser));
136 | await TriggerEventAndWait(x => x.OnBrowser(_browser, null));
137 |
138 | _browser.Disconnected += async (_, targetBrowser) =>
139 | await TriggerEventAndWait(x => x.OnDisconnected(targetBrowser, null));
140 |
141 | await TriggerEventAndWait(x => x.AfterLaunch(_browser));
142 |
143 | OrderPlugins();
144 | CheckPluginRequirements(new BrowserStartContext
145 | {
146 | StartType = StartType.Connect
147 | });
148 |
149 | return this;
150 | }
151 |
152 | public async Task ConnectOverCDPAsync(string endpointURL, BrowserTypeConnectOverCDPOptions? options = null)
153 | {
154 | if (_browserTypeEnum != BrowserTypeEnum.Chromium)
155 | throw new InvalidOperationException("ConnectOverCDPAsync is only supported for chromium browser");
156 |
157 | _persistContext = true;
158 | _persistentLaunch = false;
159 |
160 | await TriggerEventAndWait(x => x.BeforeConnect(
161 | options != null
162 | ? new BrowserTypeConnectOptions
163 | {
164 | Headers = options.Headers,
165 | Timeout = options.Timeout,
166 | SlowMo = options.SlowMo
167 | }
168 | : null));
169 |
170 | _playwright = await Playwright.CreateAsync();
171 | _browser = (await _playwright[_browserTypeEnum.GetBrowserName()].ConnectOverCDPAsync(endpointURL, options));
172 | _browserContext = _browser.Contexts.First();
173 |
174 | await TriggerEventAndWait(x => x.AfterConnect(_browser));
175 | await TriggerEventAndWait(x => x.OnBrowser(_browser, null));
176 |
177 | _browser.Disconnected += async (_, targetBrowser) =>
178 | await TriggerEventAndWait(x => x.OnDisconnected(targetBrowser, null));
179 |
180 | await TriggerEventAndWait(x => x.AfterLaunch(_browser));
181 |
182 | OrderPlugins();
183 | CheckPluginRequirements(new BrowserStartContext
184 | {
185 | StartType = StartType.Connect
186 | });
187 |
188 | return this;
189 | }
190 |
191 | public Task NewPageAsync(BrowserNewPageOptions? options = default)
192 | => NewPageAsync(null, options);
193 |
194 | ///
195 | ///
196 | /// Creates a new page in a new browser context. Closing this page will close the context
197 | /// as well.
198 | ///
199 | ///
200 | /// /// User data dir to store cache
201 | /// Call options
202 | public async Task NewPageAsync(string? userDataDir = null, BrowserNewPageOptions? options = default)
203 | {
204 | options ??= new BrowserNewPageOptions();
205 |
206 | IPage page = null!;
207 |
208 | if (_persistContext)
209 | {
210 | page = await _browserContext!.NewPageAsync();
211 | page.Close += async (_, page1) => await TriggerEventAndWait(x => x.OnPageClose(page1));
212 | }
213 | else
214 | {
215 | if (_persistentLaunch)
216 | {
217 | var persistentContextOptions = options.ToPersistentContextOptions(_persistentContextOptions);
218 |
219 | await TriggerEventAndWait(x => x.BeforeContext(null, persistentContextOptions));
220 | var browserContext = await _playwright![_browserTypeEnum.GetBrowserName()]
221 | .LaunchPersistentContextAsync(_userDataDir ?? userDataDir ?? "", persistentContextOptions);
222 | await TriggerEventAndWait(x => x.OnContextCreated(browserContext, null, persistentContextOptions));
223 |
224 | await TriggerEventAndWait(x => x.OnBrowser(null, browserContext));
225 |
226 | browserContext.Close += async (_, targetBrowserContext) =>
227 | await TriggerEventAndWait(x => x.OnDisconnected(null, targetBrowserContext));
228 |
229 | _browser = browserContext.Browser;
230 |
231 | await TriggerEventAndWait(x => x.AfterLaunch(_browser));
232 |
233 | page = await browserContext.NewPageAsync();
234 | page.Close += async (_, page1) =>
235 | {
236 | await TriggerEventAndWait(x => x.OnPageClose(page1));
237 | await page1.Context.CloseAsync();
238 | };
239 | }
240 | else
241 | {
242 | var contextOptions = options.ToContextOptions(_contextOptions);
243 |
244 | await TriggerEventAndWait(x => x.BeforeContext(contextOptions, null));
245 | var browserContext = await _browser.NewContextAsync(contextOptions);
246 | await TriggerEventAndWait(x => x.OnContextCreated(browserContext, contextOptions, null));
247 |
248 | browserContext.Close += async (_, context) =>
249 | await TriggerEventAndWait(x => x.OnDisconnected(null, context));
250 |
251 | page = await browserContext.NewPageAsync();
252 | page.Close += async (_, page1) => await TriggerEventAndWait(x => x.OnPageClose(page1));
253 | }
254 | }
255 |
256 | await TriggerEventAndWait(x => x.OnPageCreated(page));
257 |
258 | page.Request += async (_, request) => await TriggerEventAndWait(x => x.OnRequest(page, request));
259 |
260 | return page;
261 | }
262 |
263 | public ValueTask DisposeAsync()
264 | {
265 | if(_browser is not null)
266 | return _browser.DisposeAsync();
267 | return _browserContext.DisposeAsync();
268 | }
269 |
270 | public async Task CloseAsync()
271 | {
272 | if(_browser is not null)
273 | await _browser.CloseAsync();
274 | if(_browserContext is not null)
275 | await _browserContext.CloseAsync();
276 | }
277 |
278 | public Task NewBrowserCDPSessionAsync()
279 | {
280 | return _browser.NewBrowserCDPSessionAsync();
281 | }
282 |
283 | public Task NewContextAsync(BrowserNewContextOptions? options = null)
284 | {
285 | return _browser.NewContextAsync();
286 | }
287 |
288 | public IBrowserType BrowserType => _browser.BrowserType;
289 | public IReadOnlyList Contexts => _browser?.Contexts ?? new []{ _browserContext! };
290 | public bool IsConnected => _browser.IsConnected;
291 | public string Version => _browser.Version;
292 |
293 | event EventHandler? IBrowser.Disconnected
294 | {
295 | add => _browser.Disconnected += value;
296 | remove => _browser.Disconnected -= value;
297 | }
298 |
299 | public async void Dispose()
300 | {
301 | await _browser.DisposeAsync();
302 | _playwright?.Dispose();
303 | }
304 |
305 | private void ResolveDependencies(PlaywrightExtraPlugin extraPlugin)
306 | {
307 | foreach (var puppeteerExtraPlugin in extraPlugin.Dependencies)
308 | {
309 | Use(puppeteerExtraPlugin);
310 | puppeteerExtraPlugin.Dependencies.ToList().ForEach(ResolveDependencies);
311 | }
312 | }
313 |
314 | private void OrderPlugins()
315 | {
316 | _plugins = _plugins.OrderBy(e => e.Requirements.Contains(PluginRequirement.RunLast)).ToList();
317 | }
318 |
319 | private void CheckPluginRequirements(BrowserStartContext context)
320 | {
321 | foreach (var puppeteerExtraPlugin in _plugins)
322 | foreach (var requirement in puppeteerExtraPlugin.Requirements)
323 | switch (context.StartType)
324 | {
325 | case StartType.Launch when requirement == PluginRequirement.Headful && context.IsHeadless:
326 | throw new NotSupportedException(
327 | $"Plugin - {puppeteerExtraPlugin.Name} is not supported in headless mode");
328 | case StartType.Connect when requirement == PluginRequirement.Launch:
329 | throw new NotSupportedException(
330 | $"Plugin - {puppeteerExtraPlugin.Name} doesn't support connect");
331 | }
332 | }
333 |
334 | private async Task TriggerEventAndWait(Func action)
335 | {
336 | try
337 | {
338 | await Task.WhenAll(_plugins.Select(action));
339 | }
340 | catch (Exception ex)
341 | {
342 | Console.WriteLine(ex);
343 | }
344 | }
345 | }
--------------------------------------------------------------------------------
/PlaywrightExtraSharp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netstandard2.0;net7.0
4 | latest
5 | enable
6 | enable
7 |
8 | 1.0.7
9 | https://github.com/gshev/playwright-extra-sharp
10 | git
11 | playwright-extra recaptcha browser-automation browser-extension browser playwright netcore stealth-client browser-testing c#
12 | https://github.com/gshev/playwright-extra-sharp
13 | MIT
14 | true
15 | README.md
16 | Playwright version update to 1.39.0
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/PlaywrightExtraSharp.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlaywrightExtraSharp", "PlaywrightExtraSharp.csproj", "{29CBD15D-6095-45F0-827C-64E246A2F23D}"
4 | EndProject
5 | Global
6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
7 | Debug|Any CPU = Debug|Any CPU
8 | Release|Any CPU = Release|Any CPU
9 | EndGlobalSection
10 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
11 | {29CBD15D-6095-45F0-827C-64E246A2F23D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
12 | {29CBD15D-6095-45F0-827C-64E246A2F23D}.Debug|Any CPU.Build.0 = Debug|Any CPU
13 | {29CBD15D-6095-45F0-827C-64E246A2F23D}.Release|Any CPU.ActiveCfg = Release|Any CPU
14 | {29CBD15D-6095-45F0-827C-64E246A2F23D}.Release|Any CPU.Build.0 = Release|Any CPU
15 | EndGlobalSection
16 | EndGlobal
17 |
--------------------------------------------------------------------------------
/Plugins/AnonymizeUa/AnonymizeUaExtraPlugin.cs:
--------------------------------------------------------------------------------
1 | using System.Text.RegularExpressions;
2 | using Microsoft.Playwright;
3 | using PlaywrightExtraSharp.Models;
4 |
5 | namespace PlaywrightExtraSharp.Plugins.AnonymizeUa;
6 |
7 | public class AnonymizeUaExtraPlugin : PlaywrightExtraPlugin
8 | {
9 | private Func? _customAction;
10 | public override string Name => "anonymize-ua";
11 |
12 | public override Func OnPageCreated => async page =>
13 | {
14 | var ua = await page.EvaluateAsync("() => navigator.userAgent");
15 | ua = ua.Replace("HeadlessChrome", "Chrome");
16 |
17 | var uaVersion = ua.Contains("Chrome/")
18 | ? Regex.Match(ua, @"Chrome\/([\d|.]+)").Groups[1].Value
19 | : Regex.Match(ua, @"\/([\d|.]+)").Groups is { } groups
20 | ? groups[groups.Count - 1].Value
21 | : "";
22 |
23 | var regex = new Regex(@"/\(([^)]+)\)/");
24 | ua = regex.Replace(ua, "(Windows NT 10.0; Win64; x64)");
25 |
26 | if (_customAction != null)
27 | ua = _customAction(ua);
28 |
29 | var platform = GetPlatform(ua);
30 | var brand = GetBrands(uaVersion);
31 |
32 | var isMobile = GetIsMobile(ua);
33 | var platformVersion = GetPlatformVersion(ua);
34 | var platformArch = GetPlatformArch(isMobile);
35 | var platformModel = GetPlatformModel(isMobile, ua);
36 |
37 | var overrideObject = new Dictionary
38 | {
39 | { "userAgent", ua },
40 | { "platform", platform },
41 | { "acceptLanguage", "en-US, en" },
42 | {
43 | "userAgentMetadata", new Dictionary
44 | {
45 | { "brands", brand.ToArray() },
46 | { "fullVersion", uaVersion },
47 | { "platform", platform },
48 | { "platformVersion", platformVersion },
49 | { "architecture", platformArch },
50 | { "model", platformModel },
51 | { "mobile", isMobile }
52 | }
53 | }
54 | };
55 |
56 | var session = await page.Context.NewCDPSessionAsync(page);
57 | await session.SendAsync("Network.setUserAgentOverride", overrideObject);
58 | };
59 |
60 | public void CustomizeUa(Func? uaAction = default)
61 | {
62 | _customAction = uaAction;
63 | }
64 |
65 | private string GetPlatform(string ua)
66 | {
67 | if (ua.Contains("Mac OS X")) return "Mac OS X";
68 |
69 | if (ua.Contains("Android")) return "Android";
70 |
71 | if (ua.Contains("Linux")) return "Linux";
72 |
73 | return "Windows";
74 | }
75 |
76 | private string GetPlatformVersion(string ua)
77 | {
78 | if (ua.Contains("Mac OS X ")) return Regex.Match(ua, "Mac OS X ([^)]+)").Groups[1].Value;
79 |
80 | if (ua.Contains("Android ")) return Regex.Match(ua, "Android ([^;]+)").Groups[1].Value;
81 |
82 | if (ua.Contains("Windows ")) return Regex.Match(ua, @"Windows .*?([\d|.]+);").Groups[1].Value;
83 |
84 | return string.Empty;
85 | }
86 |
87 | private string GetPlatformArch(bool isMobile)
88 | {
89 | return isMobile ? string.Empty : "x86";
90 | }
91 |
92 | protected string GetPlatformModel(bool isMobile, string ua)
93 | {
94 | return isMobile ? Regex.Match(ua, @"Android.*?;\s([^)]+)").Groups[1].Value : string.Empty;
95 | }
96 |
97 | private bool GetIsMobile(string ua)
98 | {
99 | return ua.Contains("Android");
100 | }
101 |
102 | private List GetBrands(string uaVersion)
103 | {
104 | var seed = int.Parse(uaVersion.Split('.')[0]);
105 |
106 | var order = new List>
107 | {
108 | new()
109 | {
110 | 0, 1, 2
111 | },
112 | new()
113 | {
114 | 0, 2, 1
115 | },
116 | new()
117 | {
118 | 1, 0, 2
119 | },
120 | new()
121 | {
122 | 1, 2, 0
123 | },
124 | new()
125 | {
126 | 2, 0, 1
127 | },
128 | new()
129 | {
130 | 2, 1, 0
131 | }
132 | }[seed % 6];
133 |
134 | var escapedChars = new List
135 | {
136 | " ",
137 | " ",
138 | ";"
139 | };
140 |
141 | var greaseyBrand = $"{escapedChars[order[0]]}Not{escapedChars[order[1]]}A{escapedChars[order[2]]}Brand";
142 | var greasedBrandVersionList = new Dictionary();
143 |
144 | greasedBrandVersionList.Add(order[0], new UserAgentBrand
145 | (
146 | greaseyBrand,
147 | "99"
148 | ));
149 | greasedBrandVersionList.Add(order[1], new UserAgentBrand
150 | (
151 | "Chromium",
152 | seed.ToString()
153 | ));
154 |
155 | greasedBrandVersionList.Add(order[2], new UserAgentBrand
156 | (
157 | "Google Chrome",
158 | seed.ToString()
159 | ));
160 |
161 | return greasedBrandVersionList.OrderBy(e => e.Key).Select(e => e.Value).ToList();
162 | }
163 | }
--------------------------------------------------------------------------------
/Plugins/BlockResources/BlockResourcesExtraPlugin.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.BlockResources;
4 |
5 | public class BlockResourcesExtraPlugin : PlaywrightExtraPlugin
6 | {
7 | private readonly List _blockResources = new();
8 |
9 | public BlockResourcesExtraPlugin(IEnumerable? blockResources = null, string? blockPattern = null)
10 | {
11 | if (blockResources != null)
12 | _blockResources.Add(new BlockRule(resourceType: blockResources));
13 | if (blockPattern != null)
14 | _blockResources.Add(new BlockRule(sitePattern: blockPattern));
15 | }
16 |
17 | public override string Name => "block-resources";
18 |
19 | public override Func OnRequest =>
20 | (page, request) =>
21 | {
22 | var tcs = new TaskCompletionSource();
23 |
24 | page.RouteAsync("**/*", async route =>
25 | {
26 | if (_blockResources.Any(rule => rule.IsRequestBlocked(page, request)))
27 | await route.AbortAsync();
28 | else
29 | await route.ContinueAsync();
30 |
31 | tcs.SetResult(true);
32 | });
33 |
34 | return tcs.Task;
35 | };
36 |
37 | public override Func BeforeLaunch => (options1, options2) =>
38 | {
39 | if (options1 != null)
40 | options1.Args = options1.Args?.Append("--site-per-process").Append("--disable-features=IsolateOrigins")
41 | .ToArray();
42 |
43 | if (options2 != null)
44 | options2.Args = options2.Args?.Append("--site-per-process").Append("--disable-features=IsolateOrigins")
45 | .ToArray();
46 |
47 | return Task.CompletedTask;
48 | };
49 |
50 | private async Task OnPageRequest(object sender, IRequest request, TaskCompletionSource tcs)
51 | {
52 | if (sender is not IPage senderPage)
53 | {
54 | tcs.SetResult(true);
55 | return;
56 | }
57 |
58 | await senderPage.RouteAsync("**/*", async route =>
59 | {
60 | if (_blockResources.Any(rule => rule.IsRequestBlocked(senderPage, request)))
61 | await route.AbortAsync();
62 | else
63 | await route.ContinueAsync();
64 |
65 | tcs.SetResult(true);
66 | });
67 | }
68 | }
--------------------------------------------------------------------------------
/Plugins/BlockResources/BlockRule.cs:
--------------------------------------------------------------------------------
1 | using System.Text.RegularExpressions;
2 | using Microsoft.Playwright;
3 |
4 | namespace PlaywrightExtraSharp.Plugins.BlockResources;
5 |
6 | public class BlockRule
7 | {
8 | private readonly IPage? _page;
9 | private readonly IEnumerable? _resourceType;
10 | private readonly string? _sitePattern;
11 |
12 | public BlockRule(IPage? page = null, string? sitePattern = null, IEnumerable? resourceType = null)
13 | {
14 | _page = page;
15 | _sitePattern = sitePattern;
16 | _resourceType = resourceType;
17 | }
18 |
19 | public bool IsRequestBlocked(IPage? fromPage, IRequest request)
20 | {
21 | return IsResourcesBlocked(request.ResourceType) || IsSiteBlocked(request.Url) || IsPageBlocked(fromPage);
22 | }
23 |
24 |
25 | private bool IsPageBlocked(IPage? page)
26 | {
27 | return _page != null && page.Equals(_page);
28 | }
29 |
30 | private bool IsSiteBlocked(string siteUrl)
31 | {
32 | return !string.IsNullOrWhiteSpace(_sitePattern) && Regex.IsMatch(siteUrl, _sitePattern!);
33 | }
34 |
35 | private bool IsResourcesBlocked(string resource)
36 | {
37 | return _resourceType?.Contains(resource) ?? false;
38 | }
39 | }
--------------------------------------------------------------------------------
/Plugins/DisposeContext.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins;
4 |
5 | public class DisposeContext : PlaywrightExtraPlugin
6 | {
7 | public override string Name => "dispose-context";
8 |
9 | public override Func OnPageClose => page =>
10 | {
11 | //Console.WriteLine("Disposing page");
12 | return page.Context.DisposeAsync().AsTask();
13 | };
14 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/ChromeApp.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 | using Microsoft.Playwright;
3 |
4 | [assembly: InternalsVisibleTo("Extra.Tests")]
5 |
6 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
7 |
8 | public class ChromeApp : PlaywrightExtraPlugin
9 | {
10 | public override string Name => "stealth-chromeApp";
11 |
12 | public override Func OnPageCreated => page => EvaluateScript(page, "ChromeApp.js");
13 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/ChromeRuntime.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
4 |
5 | public class ChromeRuntime : PlaywrightExtraPlugin
6 | {
7 | public override string Name => "stealth-runtime";
8 |
9 | public override Func OnPageCreated => page => EvaluateScript(page, "Runtime.js");
10 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/ChromeSci.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
4 |
5 | public class ChromeSci : PlaywrightExtraPlugin
6 | {
7 | public override string Name => "stealth_sci";
8 |
9 | public override Func OnPageCreated => page => EvaluateScript(page, "SCI.js");
10 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/Codec.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
4 |
5 | public class Codec : PlaywrightExtraPlugin
6 | {
7 | public override string Name => "stealth-codec";
8 |
9 | public override Func OnPageCreated => page => EvaluateScript(page, "Codec.js");
10 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/ContentWindow.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 | using PlaywrightExtraSharp.Models;
3 |
4 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
5 |
6 | public class ContentWindow : PlaywrightExtraPlugin
7 | {
8 | public override string Name => "Iframe.ContentWindow";
9 |
10 | public override PluginRequirement[] Requirements => new[]
11 | {
12 | PluginRequirement.RunLast
13 | };
14 |
15 | public override Func OnPageCreated => page => EvaluateScript(page, "ContentWindow.js");
16 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/ExtraPluginEvasion.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
4 |
5 | public class ExtraPluginEvasion : PlaywrightExtraPlugin
6 | {
7 | public override string Name => "stealth-pluginEvasion";
8 |
9 | public override Func OnPageCreated => page => EvaluateScript(page, "Plugin.js");
10 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/HardwareConcurrency.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
4 |
5 | public class HardwareConcurrency : PlaywrightExtraPlugin
6 | {
7 | private readonly StealthHardwareConcurrencyOptions _options;
8 |
9 | public HardwareConcurrency(StealthHardwareConcurrencyOptions? options = null)
10 | {
11 | _options = options ?? new StealthHardwareConcurrencyOptions(4);
12 | }
13 |
14 | public override string Name => "stealth/hardwareConcurrency";
15 |
16 | public override Func OnPageCreated =>
17 | page => EvaluateScript(page, "HardwareConcurrency.js", _options.Concurrency);
18 | }
19 |
20 | public class StealthHardwareConcurrencyOptions : IPlaywrightExtraPluginOptions
21 | {
22 | public StealthHardwareConcurrencyOptions(int concurrency)
23 | {
24 | Concurrency = concurrency;
25 | }
26 |
27 | public int Concurrency { get; }
28 | }
--------------------------------------------------------------------------------
/Plugins/ExtraStealth/Evasions/Languages.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Playwright;
2 |
3 | namespace PlaywrightExtraSharp.Plugins.ExtraStealth.Evasions;
4 |
5 | public class Languages : PlaywrightExtraPlugin
6 | {
7 | private readonly StealthLanguagesOptions _options;
8 |
9 | public Languages(StealthLanguagesOptions? options = null)
10 | {
11 | _options = options ?? new StealthLanguagesOptions("en-US", "en");
12 | }
13 |
14 | public override string Name => "stealth-language";
15 |
16 | public override Func OnPageCreated => page => EvaluateScript(page, "Language.js", _options.Languages);
17 | }
18 |
19 | public class StealthLanguagesOptions : IPlaywrightExtraPluginOptions
20 | {
21 | public StealthLanguagesOptions(params string[] languages)
22 | {
23 | Languages = languages.Cast