Search code examples
c#puppeteer-sharp

PuppeteerSharp error No connection could be made because the target machine actively refused it 127.0.0.1:Port


I have PuppeteerSharp project and I need to save the cookies, so I use the following code:

browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
        Headless = true,
        UserDataDir = Path.Combine(".", "user-data-dir"),
});

I get error this error

No connection could be made because the target machine actively refused it 127.0.0.1:PortNumber

But when I set the Headless to false, it run without any problem. When I googled for the error message, most solutions says it about the firewall, so I turned off the firewall but nothing changes.


Solution

  • After reading this issue, it seems that we should use absolute path with UserDataDir, so this works fine:

    browser = await Puppeteer.LaunchAsync(new LaunchOptions
    {
        Headless = true,
        UserDataDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".local-chromium", "Win64-884014", "chrome-win", "UserData").Replace(@"\", @"\\")
    });
    

    But another problem appeared because browser doesn't save any cookie. Again, some issues on github said that the browser should be closed in order to save the cookies. I tried this:

    await page.CloseAsync();
    await browser.CloseAsync();
    

    But it doesn't works as expected because the browser is still running in the background. The final solution for my was this:

    var chromes = System.Diagnostics.Process.GetProcesses().Where(x => x.ProcessName == "chrome").ToList();
    
    foreach (var ch in chromes)
    {
        try
        {
            ch.Kill();
        }
        catch
        {
        }
    }
    

    The above code will close all chrome browsers, so it may need some changes in order to close the current browser only.