Search code examples
javascriptcookiesautomationgmailpuppeteer

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


so what i want to do is to open an already signed in gmail account, i used this answer here by wolfy but the thing is that it would sign you out of the account after a while or when i open multiple instances with the same cookies and u have to enter the password again

here how i did it

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
}

how i sent 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')

Solution

  • As we spoke about in the comments, I am going to try and replicate this issue to see if I can find a proper solution for you. However, one idea you can try is restoring the cookies before you close the browser each time. You can just call your getCookies method again and it should get the most updated version of your cookies (as they would have changed since the last time).