简体   繁体   中英

PuppeteerSharp - How to connect BrowserWSEndpoint using local IP address?

According to this post, it's possible to connect puppeteer to a local IP Address using the http-proxy node module. But how can I achieve this within PupperSharp(C#)? Is there any equivalent nuget library?

more context: If you launch the PuppeteerSharp on a host, get it's websocket URL and change it's host:

var browser = await Puppeteer.LaunchAsync(new() { Headless = false });
Console.WriteLine(new UriBuilder(browser.WebSocketEndpoint){ Host = "192.168.0.199" });

and in another host try to connect:

await Puppeteer.ConnectAsync(new(){ BrowserWSEndpoint = "ws://192.168.0.199:60597/devtools/browser/5f79c230-7e69-49f5-8f12-816c343cf4f8" })

connection refused exception shows.

Yarp Reverse proxy with Direct Forwarding is the answer:

Server code: (ASP.NET core minimal API):

Dictionary<string, string> routes = new();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.Map("/connect/{**catch-all}", async httpContext =>
    {
        var route = httpContext.Request.GetDisplayUrl();

        await app.Services.GetRequiredService<IHttpForwarder>().SendAsync(
            httpContext,
            routes.TryGetValue(Path.GetFileName(new Uri(route).AbsolutePath), out string targetRoute) ? targetRoute : route,
            new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy = false,
                AllowAutoRedirect = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies = false,
                ActivityHeadersPropagator = new ReverseProxyPropagator(DistributedContextPropagator.Current)
            })
        );
    });
});

app.MapGet("/", async () =>
{
    var b = await Puppeteer.LaunchAsync(new()
    {
        ExecutablePath = browserPath // set your chrome directory
    });

    var id = Path.GetFileName(b.WebSocketEndpoint);

    routes.Add(id, b.WebSocketEndpoint);

    return $"ws://your-server-ip-address/connect/{id}";
});

app.Run();

Client code:

await Puppeteer.ConnectAsync(new() { BrowserWSEndpoint = await httpClient.GetStringAsync("http://your-server-ip-address") })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM