Tuesday, 18 July 2023

Playwright: Read the cookies

'page.context().cookies()' return method returns all cookies.

 

Signature

List<Cookie> cookies()
List<Cookie> cookies(String urls);
List<Cookie> cookies(List<String> urls);

 

If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

 

Find the below working application.

 

ReadCookies.java

 

package com.sample.app.miscellaneous;

import java.util.List;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.Cookie;

public class ReadCookies {

	private static String cookieAsStr(Cookie cookie) {

		return "Cookie [name=" + cookie.name + ", value=" + cookie.value + ", url=" + cookie.url + ", domain="
				+ cookie.domain + ", path=" + cookie.path + ", expires=" + cookie.expires + ", httpOnly="
				+ cookie.httpOnly + ", secure=" + cookie.secure + ", sameSite=" + cookie.sameSite + "]";

	}

	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create();
				Browser browser = playwright.chromium()
						.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
				Page page = browser.newPage();) {

			page.navigate("https://self-learning-java-tutorial.blogspot.com/2014/03/features-of-java.html");

			System.out.println("Print all the cookies");
			List<Cookie> cookies = page.context().cookies();
			for (Cookie cookie : cookies) {
				System.out.println(cookieAsStr(cookie));
			}

		}
	}

}

If you want to maintain a login session across multiple page instances, you can set the cookies of one browser context to other page context.

Page page1 = browser1.newPage();
page1.navigate("some_url");
List<Cookie> cookies = page1.context().cookies();
			
Page page2 = browser2.newPage();
page2.context().addCookies(cookies);

   

Previous                                                 Next                                                 Home

No comments:

Post a Comment