Search code examples
c#puppeteer-sharp

How do you set a cookie in Puppetteer-Sharp?


I am attempting to set a cookie in Puppetteer-Sharp, go to a page, and read the innerHtml of an element on the page, however, it appears that the cookie is never set. How do I appropriately set a cookie in Puppetteer-Sharp?

public async Task<string> RenderPage(string baseUrl, string url, string cookieName, string cookieValue)
    {
      await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
      using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))      
      {
        using (var page = await browser.NewPageAsync())
        {
          await page.SetCookieAsync(new CookieParam { 
            Name = cookieName, 
            Value = cookieValue, 
            Domain = baseUrl, 
            Url = baseUrl + url 
          });
          await page.GoToAsync(baseUrl + url);
          await page.WaitForSelectorAsync("table.summary-table");
          var cookies = await page.GetCookiesAsync(baseUrl + url);
          var element = await page.QuerySelectorAsync("html");
          var text = await (await element.GetPropertyAsync("innerHTML")).JsonValueAsync<string>();
          Console.WriteLine(text);
          return text;
        }
      }
    }

From the Chromium dev console, you can see that there are no cookies for the domain: no cookies

From the visual studio debugger, you can see that Puppeteer thinks there are no cookies set on the page:

no cookies on the page


Solution

  • You have to be careful with your domain property. If it's not valid, it will be ignored. For what I see there. You might be setting something like http://www.yourdomain.com, when yourdomain.com is expected.