Skip to content

Commit 13d6704

Browse files
authored
Fix browser check in Page.ScreenshotAsync (#2373)
1 parent 0c9362c commit 13d6704

File tree

5 files changed

+58
-55
lines changed

5 files changed

+58
-55
lines changed

lib/PuppeteerSharp/Browser.cs

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,10 @@
33
using System.Collections.Generic;
44
using System.Diagnostics;
55
using System.Linq;
6-
using System.Runtime.InteropServices;
76
using System.Threading.Tasks;
87
using Microsoft.Extensions.Logging;
98
using PuppeteerSharp.Helpers;
10-
using PuppeteerSharp.Helpers.Json;
119
using PuppeteerSharp.Messaging;
12-
using PuppeteerSharp.QueryHandlers;
1310

1411
namespace PuppeteerSharp
1512
{
@@ -37,6 +34,7 @@ internal Browser(
3734
Func<Target, bool> targetFilter = null,
3835
Func<Target, bool> isPageTargetFunc = null)
3936
{
37+
BrowserType = browser;
4038
IgnoreHTTPSErrors = ignoreHTTPSErrors;
4139
DefaultViewport = defaultViewport;
4240
Launcher = launcher;
@@ -96,6 +94,9 @@ internal Browser(
9694
/// <inheritdoc/>
9795
public string WebSocketEndpoint => Connection.Url;
9896

97+
/// <inheritdoc/>
98+
public SupportedBrowser BrowserType { get; }
99+
99100
/// <inheritdoc/>
100101
public Process Process => Launcher?.Process;
101102

lib/PuppeteerSharp/IBrowser.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using System.Diagnostics;
33
using System.Threading.Tasks;
44
using Microsoft.Extensions.Logging;
5-
using PuppeteerSharp.QueryHandlers;
65

76
namespace PuppeteerSharp
87
{
@@ -70,6 +69,11 @@ public interface IBrowser : IDisposable, IAsyncDisposable
7069
/// <value>The default context.</value>
7170
IBrowserContext DefaultContext { get; }
7271

72+
/// <summary>
73+
/// Returns the browser type. Chrome, Chromium or Firefox.
74+
/// </summary>
75+
SupportedBrowser BrowserType { get; }
76+
7377
/// <summary>
7478
/// Default wait time in milliseconds. Defaults to 30 seconds.
7579
/// </summary>

lib/PuppeteerSharp/Page.cs

+44-44
Original file line numberDiff line numberDiff line change
@@ -239,15 +239,15 @@ public int DefaultTimeout
239239

240240
internal bool IsDragging { get; set; }
241241

242-
internal Browser Browser => Target.Browser;
242+
internal bool HasPopupEventListeners => Popup?.GetInvocationList().Any() == true;
243243

244-
internal Target Target { get; }
244+
private Browser Browser => Target.Browser;
245245

246-
internal bool JavascriptEnabled { get; set; } = true;
246+
private Target Target { get; }
247247

248-
internal bool HasPopupEventListeners => Popup?.GetInvocationList().Any() == true;
248+
private bool JavascriptEnabled { get; set; } = true;
249249

250-
internal FrameManager FrameManager { get; private set; }
250+
private FrameManager FrameManager { get; set; }
251251

252252
private Task SessionClosedTask
253253
{
@@ -405,7 +405,7 @@ public Task SetRequestInterceptionAsync(bool value)
405405
public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)
406406
=> (await Client.SendAsync<NetworkGetCookiesResponse>("Network.getCookies", new NetworkGetCookiesRequest
407407
{
408-
Urls = urls.Length > 0 ? urls : new string[] { Url },
408+
Urls = urls.Length > 0 ? urls : new[] { Url },
409409
}).ConfigureAwait(false)).Cookies;
410410

411411
/// <inheritdoc/>
@@ -620,10 +620,8 @@ public async Task ScreenshotAsync(string file, ScreenshotOptions options)
620620

621621
var data = await ScreenshotDataAsync(options).ConfigureAwait(false);
622622

623-
using (var fs = AsyncFileHelper.CreateStream(file, FileMode.Create))
624-
{
625-
await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
626-
}
623+
using var fs = AsyncFileHelper.CreateStream(file, FileMode.Create);
624+
await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
627625
}
628626

629627
/// <inheritdoc/>
@@ -659,12 +657,12 @@ public Task<string> ScreenshotBase64Async(ScreenshotOptions options)
659657
}
660658
}
661659

662-
if (options?.Clip?.Width == 0)
660+
if (options.Clip?.Width == 0)
663661
{
664662
throw new PuppeteerException("Expected options.Clip.Width not to be 0.");
665663
}
666664

667-
if (options?.Clip?.Height == 0)
665+
if (options.Clip?.Height == 0)
668666
{
669667
throw new PuppeteerException("Expected options.Clip.Height not to be 0.");
670668
}
@@ -826,7 +824,7 @@ public async Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = nu
826824
Interval = idleTime,
827825
};
828826

829-
idleTimer.Elapsed += (sender, args) =>
827+
idleTimer.Elapsed += (_, _) =>
830828
{
831829
networkIdleTcs.TrySetResult(true);
832830
};
@@ -1098,7 +1096,7 @@ await Client.SendAsync(
10981096
/// <inheritdoc/>
10991097
public Task EmulateCPUThrottlingAsync(decimal? factor = null)
11001098
{
1101-
if (factor != null && factor < 1)
1099+
if (factor is < 1)
11021100
{
11031101
throw new ArgumentException("Throttling rate should be greater or equal to 1", nameof(factor));
11041102
}
@@ -1150,7 +1148,19 @@ internal static async Task<Page> CreateAsync(
11501148
}
11511149
}
11521150

1153-
internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)
1151+
internal void OnPopup(IPage popupPage) => Popup?.Invoke(this, new PopupEventArgs { PopupPage = popupPage });
1152+
1153+
/// <summary>
1154+
/// Dispose resources.
1155+
/// </summary>
1156+
/// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>
1157+
protected virtual void Dispose(bool disposing)
1158+
{
1159+
Mouse.Dispose();
1160+
_ = DisposeAsync();
1161+
}
1162+
1163+
private async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)
11541164
{
11551165
var paperWidth = PaperFormat.Letter.Width;
11561166
var paperHeight = PaperFormat.Letter.Height;
@@ -1211,18 +1221,6 @@ internal async Task<byte[]> PdfInternalAsync(string file, PdfOptions options)
12111221
return await ProtocolStreamReader.ReadProtocolStreamByteAsync(Client, result.Stream, file).ConfigureAwait(false);
12121222
}
12131223

1214-
internal void OnPopup(IPage popupPage) => Popup?.Invoke(this, new PopupEventArgs { PopupPage = popupPage });
1215-
1216-
/// <summary>
1217-
/// Dispose resources.
1218-
/// </summary>
1219-
/// <param name="disposing">Indicates whether disposal was initiated by <see cref="Dispose()"/> operation.</param>
1220-
protected virtual void Dispose(bool disposing)
1221-
{
1222-
Mouse.Dispose();
1223-
_ = DisposeAsync();
1224-
}
1225-
12261224
private async Task InitializeAsync()
12271225
{
12281226
await FrameManager.InitializeAsync().ConfigureAwait(false);
@@ -1240,8 +1238,8 @@ private async Task InitializeAsync()
12401238
networkManager.RequestServedFromCache += (_, e) => RequestServedFromCache?.Invoke(this, e);
12411239

12421240
await Task.WhenAll(
1243-
Client.SendAsync("Performance.enable", null),
1244-
Client.SendAsync("Log.enable", null)).ConfigureAwait(false);
1241+
Client.SendAsync("Performance.enable"),
1242+
Client.SendAsync("Log.enable")).ConfigureAwait(false);
12451243
}
12461244

12471245
private async Task<IResponse> GoAsync(int delta, NavigationOptions options)
@@ -1293,7 +1291,7 @@ private async Task<string> PerformScreenshot(ScreenshotType type, ScreenshotOpti
12931291

12941292
// FromSurface is not supported on Firefox.
12951293
// It seems that Puppeteer solved this just by ignoring screenshot tests in firefox.
1296-
if (Browser.Launcher.Options.Browser == SupportedBrowser.Firefox)
1294+
if (Browser.BrowserType == SupportedBrowser.Firefox)
12971295
{
12981296
if (options.FromSurface != null)
12991297
{
@@ -1302,15 +1300,15 @@ private async Task<string> PerformScreenshot(ScreenshotType type, ScreenshotOpti
13021300
}
13031301
else
13041302
{
1305-
options.FromSurface = options.FromSurface.HasValue ? options.FromSurface : true;
1303+
options.FromSurface ??= true;
13061304
}
13071305

13081306
var clip = options.Clip != null ? ProcessClip(options.Clip) : null;
13091307
var captureBeyondViewport = options.CaptureBeyondViewport;
13101308

13111309
if (!_screenshotBurstModeOn)
13121310
{
1313-
if (options?.FullPage == true)
1311+
if (options.FullPage)
13141312
{
13151313
// Overwrite clip for full page at all times.
13161314
clip = null;
@@ -1356,13 +1354,13 @@ private async Task<string> PerformScreenshot(ScreenshotType type, ScreenshotOpti
13561354
}
13571355
}
13581356

1359-
if (options?.OmitBackground == true && type == ScreenshotType.Png)
1357+
if (options.OmitBackground && type == ScreenshotType.Png)
13601358
{
13611359
await SetTransparentBackgroundColorAsync().ConfigureAwait(false);
13621360
}
13631361
}
13641362

1365-
if (options?.FullPage == false && clip == null)
1363+
if (options.FullPage == false && clip == null)
13661364
{
13671365
captureBeyondViewport = false;
13681366
}
@@ -1417,7 +1415,7 @@ private Clip ProcessClip(Clip clip)
14171415

14181416
private Task ResetBackgroundColorAndViewportAsync(ScreenshotOptions options)
14191417
{
1420-
var omitBackgroundTask = options?.OmitBackground == true && options.Type == ScreenshotType.Png ?
1418+
var omitBackgroundTask = options is { OmitBackground: true, Type: ScreenshotType.Png } ?
14211419
ResetDefaultBackgroundColorAsync() : Task.CompletedTask;
14221420
var setViewPortTask = (options?.FullPage == true && Viewport != null) ?
14231421
SetViewportAsync(Viewport) : Task.CompletedTask;
@@ -1604,7 +1602,7 @@ private async Task OnLogEntryAddedAsync(LogEntryAddedResponse e)
16041602
{
16051603
if (e.Entry.Args != null)
16061604
{
1607-
foreach (var arg in e.Entry?.Args)
1605+
foreach (var arg in e.Entry.Args)
16081606
{
16091607
await RemoteObjectHelper.ReleaseObjectAsync(Client, arg, _logger).ConfigureAwait(false);
16101608
}
@@ -1648,14 +1646,16 @@ private string GetExceptionMessage(EvaluateExceptionResponseDetails exceptionDet
16481646
}
16491647

16501648
var message = exceptionDetails.Text;
1651-
if (exceptionDetails.StackTrace != null)
1649+
if (exceptionDetails.StackTrace == null)
16521650
{
1653-
foreach (var callframe in exceptionDetails.StackTrace.CallFrames)
1654-
{
1655-
var location = $"{callframe.Url}:{callframe.LineNumber}:{callframe.ColumnNumber}";
1656-
var functionName = callframe.FunctionName ?? "<anonymous>";
1657-
message += $"\n at {functionName} ({location})";
1658-
}
1651+
return message;
1652+
}
1653+
1654+
foreach (var callFrame in exceptionDetails.StackTrace.CallFrames)
1655+
{
1656+
var location = $"{callFrame.Url}:{callFrame.LineNumber}:{callFrame.ColumnNumber}";
1657+
var functionName = callFrame.FunctionName ?? "<anonymous>";
1658+
message += $"\n at {functionName} ({location})";
16591659
}
16601660

16611661
return message;
@@ -1732,7 +1732,7 @@ await Task.WhenAll(Frames.Select(
17321732
.ContinueWith(
17331733
task =>
17341734
{
1735-
if (task.IsFaulted)
1735+
if (task.IsFaulted && task.Exception != null)
17361736
{
17371737
_logger.LogError(task.Exception.ToString());
17381738
}

lib/PuppeteerSharp/Puppeteer.cs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System;
21
using System.Collections.Generic;
3-
using System.Text.RegularExpressions;
42
using System.Threading.Tasks;
53
using Microsoft.Extensions.Logging;
64
using PuppeteerSharp.Mobile;
@@ -41,7 +39,7 @@ public static class Puppeteer
4139
public static IReadOnlyDictionary<DeviceDescriptorName, DeviceDescriptor> Devices => DeviceDescriptors.ToReadOnly();
4240

4341
/// <summary>
44-
/// Returns a list of network conditions to be used with <seealso cref="IPage.EmulateNetworkConditionsAsync(NetworkConditions)"/>.
42+
/// Returns a list of network conditions to be used with <seealso cref="IPage.EmulateNetworkConditionsAsync(PuppeteerSharp.NetworkConditions)"/>.
4543
/// Actual list of conditions can be found in <seealso cref="PredefinedNetworkConditions.Conditions"/>.
4644
/// </summary>
4745
/// <example>

lib/PuppeteerSharp/PuppeteerSharp.csproj

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@
1212
<Description>Headless Browser .NET API</Description>
1313
<PackageId>PuppeteerSharp</PackageId>
1414
<PackageReleaseNotes></PackageReleaseNotes>
15-
<PackageVersion>13.0.1</PackageVersion>
16-
<ReleaseVersion>13.0.1</ReleaseVersion>
17-
<AssemblyVersion>13.0.1</AssemblyVersion>
18-
<FileVersion>13.0.1</FileVersion>
15+
<PackageVersion>13.0.2</PackageVersion>
16+
<ReleaseVersion>13.0.2</ReleaseVersion>
17+
<AssemblyVersion>13.0.2</AssemblyVersion>
18+
<FileVersion>13.0.2</FileVersion>
1919
<SynchReleaseVersion>false</SynchReleaseVersion>
2020
<StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
2121
<DebugType>embedded</DebugType>

0 commit comments

Comments
 (0)