Home > Mobile >  Is there any way to use cookies&caches to skip the login process with C# and Playwright?
Is there any way to use cookies&caches to skip the login process with C# and Playwright?

Time:12-29

using Microsoft.Playwright;
using NUnit.Framework;

namespace test;
public class SkipLogin
{

    [SetUp]
    public void Setup()
    {
        
    }

    [Test]
    public async Task Test1()
    {
        using var playwright = await Playwright.CreateAsync();

        await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
        {
            Headless = false
        });
        var context = await browser.NewContextAsync(new BrowserNewContextOptions
        {
            StorageState = "userCookies.json"
        });
        var page = await context.NewPageAsync();
        await page.GotoAsync("https://example.com");
        

    }

}

I'm new to C# Playwright and I'm trying to skip the login process by using "userCookies.json".

So, after logging in, I stored all cookies and caches and copied them to my folder. After that, I want to create a browser context with my cookies. But I'm getting this:

System.AggregateException: One or more errors occurred. ('e' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.) (Interf...

System.AggregateException
One or more errors occurred. ('e' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.) (Interface cannot be resolved: Microsoft.Playwright.IBrowser)
  Exception doesn't have a stacktrace

I tried it with JavaScript and Playwright it could be doable,but I don't how to handle it.

CodePudding user response:

According to their documentation it should be possible. I see you are using StorageState maybe try StorageStatePath instead. Their example:

var context = await browser.NewContextAsync(new()
{
    StorageStatePath = "userCookies.json"
});

https://playwright.dev/dotnet/docs/auth

It's not clear from their documentation, and I never used this library before and could be wrong, but I believe StorageState expects the stringified JSON and not a file path. While StorageStatePath expects a file path / file name to the JSON and will read the file for you.

https://www.javadoc.io/static/com.microsoft.playwright/playwright/1.12.1/com/microsoft/playwright/Browser.NewContextOptions.html#storageState

  • Related