I'm using playwright and TS.
I'm currently executing my test with the default playwright setup (it's incognito if I remember correctly)
and I want to execute some tests with my own chrome profile.
I tried to search for user-XXX
or profile
properties in chromium LaunchOptions
object,
but no luck.
of course I've checked the docs and nothing.
I've asked some AI tools and no help either.
Something like this:
const browser = await chromium.launch({
channel: "chrome",
// Here is what I'm looking for
user_data_dir: "C:\\Users\\Home\\AppData\\Local\\Google\\Chrome\\User Data"
// or
user: ""
// or
profile: ""
});
Or via BrowserContext... anything would help.
I think you want the userDataDir
parameter of launchPersistentContext
:
const userDataDir = "C:\\Users\\Home\\AppData\\Local\\Google\\Chrome\\User Data";
const browser = await chromium.launchPersistentContext(
userDataDir,
{channel: "chrome"}
);
Here's a complete, minimal example.
index.html:
<!DOCTYPE html>
<html><body><script>
const result = localStorage.getItem("foo");
if (result) {
document.body.innerHTML = `<h1>${result}</h1>`;
}
else { // user's first visit, no local storage was found
localStorage.setItem("foo", "it worked");
document.body.innerHTML = `<h1>visit again...</h1>`;
}
</script></body></html>
pw.js:
const {chromium} = require("playwright"); // ^1.38.0
let browser;
(async () => {
const userDataDir = "test";
browser = await chromium.launchPersistentContext(userDataDir);
const page = await browser.newPage();
await page.goto("http://localhost:8000");
console.log(await page.locator("h1").textContent());
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
Output:
$ python -m http.server & # serve the page at http://localhost:8000
$ node pw # first run, no session exists yet
visit again...
$ node pw # second run, session is preserved
it worked
$ rm -rf test # destroy the session
$ node pw
visit again...