如何使用 puppeteer(node js)在 gmail 中保持登录状态

how to stay signed in gmail using puppeteer(node js )

所以我想做的是打开一个已经登录的 gmail 帐户,我使用了这个答案 by wolfy 但问题是它会在一段时间后或当我打开时将您从帐户中注销具有相同 cookie 的多个实例,你必须再次输入密码

我是怎么做到的

const getCookies = async (page) => {
    // Get all cookies
    const cookiesArray = await page._client.send('Network.getAllCookies');

    // Get cookies from array
    const cookies = await cookiesArray.cookies;

    // Save cookies to file
    fs.writeFile('./cookies.json', JSON.stringify(cookies, null, 4), (err) => {
        if (err) console.log(err);
        return;
    });
}

const setCookies = async (page) => {
    // Get cookies from file
    let cookies = JSON.parse(fs.readFileSync('./cookies.json'));

    // Set page cookies
    await page.setCookie(...cookies);
    return
}

我是如何发送cookies的

// Create page once browser loads
let [page] = await browser.pages();

// Turn on page request interception
await page.setRequestInterception(true);

// Add event listener on request
page.on('request', async (req) => {

    // If the request url is what I want, start my function
    if (req.url() === 'https://youtube.com/?authuser=0') {
        await getCookies(page);
        await browser.close();
    }

    // If the url is not, continue normal functionality of the page
    req.continue();
});

// Then go to my url once all the listeners are setup
await page.goto('https://accounts.google.com/AccountChooser?service=wise&continue=https://youtube.com')

正如我们在评论中所说,我将尝试复制这个问题,看看我是否能为您找到合适的解决方案。但是,您可以尝试的一种方法是在每次关闭浏览器之前恢复 cookie。您可以再次调用您的 getCookies 方法,它应该会获得您的 cookie 的最新版本(因为它们自上次以来已经发生了变化)。