首页 > 解决方案 > 如何在 playwright 中将多个 storageStates 加载到单个上下文中

问题描述

所以我想将多个 storageStates 加载到剧作家的单个上下文中,但是当我这样做时

const context = await browser.newContext({
      storageState: "telegram.json",storageState: "google.json"
    });

或这个

const context = await browser.newContext({
      storageState: ["telegram.json","google.json"]
    });

没有加载任何状态。

但是下面的代码会加载一个 storageState

const context = await browser.newContext({
      storageState: "telegram.json"
    });

我如何实现这一目标?

标签: javascriptnode.jsseleniumautomationplaywright

解决方案


你不能storageState像那样加载多个,但你可以这样做应该达到相同的结果:

const fs = require('fs-extra');
const telegramState = JSON.parse(fs.readFileSync('telegram.json'));
const googleState = JSON.parse(fs.readFileSync('google.json'));

// merge them into one
let state = { ...telegramState, ...googleState }
const context = await browser.newContext({
      storageState: state
});

这里我们只是使用了 spread (...) 操作符来合并两个 storageState 对象。

注意:

如果两个对象都有同名的属性,则第二个对象属性将覆盖第一个。

如果这是一个问题,您可以_.mergelodash尝试。


推荐阅读