Skip to content

Commit

Permalink
Introduce InitAction in browser constructor (#1871)
Browse files Browse the repository at this point in the history
  • Loading branch information
brnbs authored Nov 17, 2021
1 parent 3325a5b commit 182e95c
Show file tree
Hide file tree
Showing 8 changed files with 105 additions and 51 deletions.
37 changes: 0 additions & 37 deletions docfx_project/examples/LodCDP.md

This file was deleted.

66 changes: 66 additions & 0 deletions docfx_project/examples/LogCDPCommunication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# How to log messages between Puppeteer-Sharp and Chromium

_Contributors: [Darío Kondratiuk](https://www.hardkoded.com/), [Barnabas Szenasi](https://outisnemo.com/)_

## Problem

You want to log the messages sent by your app to Chromium and the messages received by Chromium. Below you can find two solutions for the most common logging frameworks.

## Log CDP messages to files using Serilog

Add [Serilog.Extensions.Logging.File](https://www.nuget.org/packages/Serilog.Extensions.Logging.File/) Nuget package.

First we need to create an `ILoggerFactory`

```cs
private static ILoggerFactory GetLoggerFactory(string file)
{
var factory = new LoggerFactory();
var filter = new FilterLoggerSettings
{
{ "Connection", LogLevel.Trace }
};

factory.WithFilter(filter).AddFile(file, LogLevel.Trace);

return factory;
}
```

Now we can use `GetLoggerFactory` to inject a logger into Puppeteer.

```cs
using (var browser = await Puppeteer.LaunchAsync(browserOptions, GetLoggerFactory(fileName)))
{
//Some code
}
```

## Log CDP messages to console using Microsoft.Extensions.Logging

Add [Microsoft.Extensions.Logging.Console](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Console) Nuget package.

First we need to create an `ILoggerFactory`

```cs
private static ILoggerFactory GetLoggerFactory()
{
var loggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
{
builder
.AddConsole(options => options.Format = ConsoleLoggerFormat.Systemd)
.SetMinimumLevel(LogLevel.Trace);
});

return loggerFactory;
}
```

Now we can use `GetLoggerFactory` to inject a logger into Puppeteer.LaunchAsync or Puppeteer.ConnectAsync method.

```cs
using (var browser = await Puppeteer.LaunchAsync(browserOptions, GetLoggerFactory()))
{
//Some code
}
```
2 changes: 1 addition & 1 deletion docfx_project/examples/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
- name: Advanced
items:
- name: How to log CDP communication
href: LogCDP.md
href: LogCDPCommunication.md
19 changes: 19 additions & 0 deletions lib/PuppeteerSharp.Tests/LauncherTests/PuppeteerConnectTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,25 @@ public async Task ShouldSupportTargetFilter()
}
}

[PuppeteerFact]
public async Task ShouldBeAbleToSetBrowserPropertiesUsingConnectOptions()
{
var initActionExecuted = false;
var options = new ConnectOptions
{
BrowserWSEndpoint = Browser.WebSocketEndpoint,
InitAction = brw =>
{
initActionExecuted = true;
}
};
var browser = await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory);

Assert.True(initActionExecuted);

await browser.CloseAsync();
}

[PuppeteerTest("launcher.spec.ts", "Puppeteer.connect", "should be able to reconnect to a disconnected browser")]
[SkipBrowserFact(skipFirefox: true)]
public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()
Expand Down
8 changes: 6 additions & 2 deletions lib/PuppeteerSharp/Browser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -520,10 +520,14 @@ internal static async Task<Browser> CreateAsync(
string[] contextIds,
bool ignoreHTTPSErrors,
ViewPortOptions defaultViewPort,
LauncherBase launcher,
Func<TargetInfo, bool> targetFilter)
LauncherBase launcher,
Func<TargetInfo, bool> targetFilter,
Action<Browser> initAction = null)
{
var browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewPort, launcher, targetFilter);

initAction?.Invoke(browser);

await connection.SendAsync("Target.setDiscoverTargets", new TargetSetDiscoverTargetsRequest
{
Discover = true
Expand Down
5 changes: 5 additions & 0 deletions lib/PuppeteerSharp/ConnectOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,10 @@ public class ConnectOptions : IBrowserOptions, IConnectionOptions
/// Callback to decide if Puppeteer should connect to a given target or not.
/// </summary>
public Func<TargetInfo, bool> TargetFilter { get; set; }

/// <summary>
/// Optional callback to initialize properties as soon as the <see cref="Browser"/> instance is created, i.e., set up event handlers.
/// </summary>
public Action<Browser> InitAction { get; set; }
}
}
16 changes: 6 additions & 10 deletions lib/PuppeteerSharp/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,12 @@ internal Connection(string url, int delay, bool enqueueAsyncMessages, IConnectio

internal Task RawSendASync(int id, string method, object args, string sessionId = null)
{
_logger.LogTrace("Send ► {Id} Method {Method} Params {@Params}", id, method, args);
return Transport.SendAsync(JsonConvert.SerializeObject(
new ConnectionRequest
{
Id = id,
Method = method,
Params = args,
SessionId = sessionId
},
JsonHelper.DefaultJsonSerializerSettings));
var message = JsonConvert.SerializeObject(
new ConnectionRequest { Id = id, Method = method, Params = args, SessionId = sessionId },
JsonHelper.DefaultJsonSerializerSettings);
_logger.LogTrace("Send ► {Message}", message);

return Transport.SendAsync(message);
}

internal async Task<JObject> SendAsync(string method, object args = null, bool waitForCallback = true)
Expand Down
3 changes: 2 additions & 1 deletion lib/PuppeteerSharp/Launcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ public async Task<Browser> ConnectAsync(ConnectOptions options)
options.IgnoreHTTPSErrors,
options.DefaultViewport,
null,
options.TargetFilter)
options.TargetFilter,
options.InitAction)
.ConfigureAwait(false);
}
catch (Exception ex)
Expand Down

0 comments on commit 182e95c

Please sign in to comment.