2024-02-04 22:55:46 +00:00
|
|
|
using System.IO;
|
|
|
|
|
|
2024-01-03 19:40:41 +00:00
|
|
|
namespace BotSharp.Plugin.WebDriver.Drivers.PlaywrightDriver;
|
2024-01-03 04:43:37 +00:00
|
|
|
|
|
|
|
|
public class PlaywrightInstance : IDisposable
|
|
|
|
|
{
|
|
|
|
|
IPlaywright _playwright;
|
2024-02-02 04:16:57 +00:00
|
|
|
IBrowserContext _context;
|
2024-01-03 04:43:37 +00:00
|
|
|
|
2024-02-02 04:16:57 +00:00
|
|
|
public IBrowserContext Context => _context;
|
2024-02-06 05:05:52 +00:00
|
|
|
public IPage Page
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
if (_context == null)
|
|
|
|
|
{
|
|
|
|
|
InitInstance().Wait();
|
|
|
|
|
}
|
|
|
|
|
return _context.Pages.LastOrDefault();
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-01-03 04:43:37 +00:00
|
|
|
|
2024-01-06 03:24:13 +00:00
|
|
|
public async Task InitInstance()
|
|
|
|
|
{
|
|
|
|
|
if (_playwright == null)
|
|
|
|
|
{
|
|
|
|
|
_playwright = await Playwright.CreateAsync();
|
2024-02-04 22:55:46 +00:00
|
|
|
}
|
2024-01-06 03:24:13 +00:00
|
|
|
|
2024-02-04 22:55:46 +00:00
|
|
|
if (_context == null)
|
|
|
|
|
{
|
2024-02-06 05:05:52 +00:00
|
|
|
string tempFolderPath = $"{Path.GetTempPath()}\\playwright\\{Guid.NewGuid()}";
|
2024-02-04 22:55:46 +00:00
|
|
|
_context = await _playwright.Chromium.LaunchPersistentContextAsync(tempFolderPath, new BrowserTypeLaunchPersistentContextOptions
|
2024-01-06 03:24:13 +00:00
|
|
|
{
|
|
|
|
|
Headless = false,
|
|
|
|
|
Channel = "chrome",
|
2024-02-05 04:22:43 +00:00
|
|
|
IgnoreDefaultArgs = new[]
|
2024-02-04 22:55:46 +00:00
|
|
|
{
|
2024-02-05 04:22:43 +00:00
|
|
|
"enable-automation"
|
|
|
|
|
},
|
|
|
|
|
Args = new[]
|
|
|
|
|
{
|
|
|
|
|
"--disable-infobars"
|
2024-02-04 22:55:46 +00:00
|
|
|
// "--start-maximized"
|
2024-01-06 22:24:22 +00:00
|
|
|
}
|
2024-01-06 03:24:13 +00:00
|
|
|
});
|
2024-02-02 04:16:57 +00:00
|
|
|
|
2024-02-04 22:55:46 +00:00
|
|
|
_context.Page += async (sender, e) =>
|
|
|
|
|
{
|
|
|
|
|
e.Close += async (sender, e) =>
|
|
|
|
|
{
|
|
|
|
|
Serilog.Log.Information($"Page is closed: {e.Url}");
|
|
|
|
|
};
|
|
|
|
|
Serilog.Log.Information($"New page is created: {e.Url}");
|
|
|
|
|
await e.SetViewportSizeAsync(1280, 800);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
_context.Close += async (sender, e) =>
|
|
|
|
|
{
|
|
|
|
|
Serilog.Log.Warning($"Playwright browser context is closed");
|
|
|
|
|
_context = null;
|
|
|
|
|
};
|
2024-01-06 03:24:13 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-01-03 04:43:37 +00:00
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
_playwright.Dispose();
|
|
|
|
|
}
|
|
|
|
|
}
|