如何使用Playwright中的现有用户配置文件启动Chrome或Chromium

h5qlskok  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(352)

我在用剧作家和TS。
我目前正在使用默认的playwright设置(如果我没记错的话,它是匿名的)执行我的测试,我想用我自己的Chrome配置文件执行一些测试。
我试图在 chrome LaunchOptions对象中搜索user-XXXprofile属性,但没有运气。
我当然查过文件什么都没查到
我问了一些人工智能工具,也没有帮助。
就像这样:

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: ""
    });

字符串
或者通过BrowserContext...任何东西都有帮助。

c6ubokkw

c6ubokkw1#

我想你需要launchPersistentContextuserDataDir参数:

const userDataDir = "C:\\Users\\Home\\AppData\\Local\\Google\\Chrome\\User Data";
const browser = await chromium.launchPersistentContext(
  userDataDir,
  {channel: "chrome"}
);

字符串
这里有一个完整的,最小的例子。
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());


输出量:

$ 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...

相关问题