Tips for maintaining a persistent login session in Gmail with Puppeteer and Node.js

I'm trying to access a pre-signed gmail account, following the guidance provided by this answer from user wolfy. However, I noticed that it logs me out after a while or when multiple instances are opened with the same cookies, requiring me to re-enter the password.

This is how I implemented it:

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

    // Extract 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) => {
    // Retrieve cookies from file
    let cookies = JSON.parse(fs.readFileSync('./cookies.json'));

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

Sending cookies:

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

// Enable page request interception
await page.setRequestInterception(true);

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

    // If the request URL matches my criteria, execute my function
    if (req.url() === 'https://youtube.com/?authuser=0') {
        await getCookies(page);
        await browser.close();
    }

    // Otherwise, continue normal functionality
    req.continue();
});

// Navigate to my desired URL once all listeners are set up
await page.goto('https://accounts.google.com/AccountChooser?service=wise&continue=https://youtube.com')

Answer №1

After our discussion in the comments, I've decided to investigate this problem further to identify a suitable resolution for you. In the meantime, one suggestion you could consider is resetting the cookies before exiting the browser each session. Simply executing your getCookies function will retrieve the latest cookie information (which may have been altered since your last use).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for achieving proper styling and formatting of elements in jQuery UI

I've encountered an issue when trying to use jQuery UI after downloading it multiple times. In the examples provided with the download, the UI elements appear perfectly formatted, but when I implement them on my own pages, the styles and formatting ge ...

Vue - Passing a parent's ref to a child component as a prop

Is there a way to pass the current component's reference to a child component in Vue.js? <template> <div class="screen" ref="screen"> <child-component :screenRef="screenRef"> </child-component> </div ...

Insert fixed text before or after the input value without altering the value itself

Is it possible to prepend or append additional text to an input value? I am looking to customize the display of a value without altering the actual value itself. For instance, if the value is 1000, I want it to still return 1000 when accessed. <input ...

What is the role of the equal sign (=) when connecting a function to an event listener in JavaScript?

What is the rationale behind using the equal sign "=" instead of the dot "." when attaching a function to an event listener in JavaScript? Normally, it is the convention to use the dot as notation for perform an action. clickme.onclick = function() { ...

Is it possible to import Vue directly from the "/path/to/vue.js" file without using npm or NodeJs?

Is it possible to build a web app using just a single index.js file and importing other available files like shown in this image: https://i.stack.imgur.com/02aFF.png encountering the error message: import not found: default Do you have to use Vuejs wit ...

Exporting State From Another ReactJS Module: A Step-by-Step Guide

A new project is underway with 3 students who are diving into the world of React for the first time. To make our work more efficient, I suggested dividing the code so that each student could work on a different aspect simultaneously. However, when I attemp ...

Getting JSON data from PHP in AngularJS involves making an HTTP request to the PHP file

I've been searching extensively, but haven't found a solution. I need the data from my PHP script to be formatted like this: $scope.places = [{name: 'John'},{name: 'Jane'}]; My issue is figuring out how to make this happen. ...

Populate DataGrid using an input through AJAX and jQuery technology

I've been grappling with a persistent issue that's been bothering me for days now. Here's the scenario: Currently, I have a DataGrid that is empty and an Input Text field in place that utilizes AJAX and jQuery to display a list of available ...

Techniques for transferring PHP print_r arrays to Javascript

Array ( [0] => Array ( [sno] => 1 [name] => Sivamani [contact] => 750241378 [$city] => Madurai ) ) Array ( [1] => Array ( [sno] => 2 ...

What vulnerabilities does Google identify in Django that make it a less secure application?

What is the reason behind Google deeming a request from my Django application to send an email through SMTP (smtp.gmail.com) as insecure? The explanation provided in their security standards seems vague: How more secure apps help protect your account When ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

JS Tips for using the .push() function with Multidimensional Arrays in JavaScript

After coming across this code example online, I decided to give it a try. The code snippet involved using the JavaScript array push method to add new elements to an inner sub-array, which was exactly what I needed to achieve! The code successfully demons ...

The JavaScript function is not being activated by clicking on Selenium in Chrome

Take a look at the HTML snippet below: <table class="table-main "> <thead> <tbody> <!----> <tr class="" ng-if="mapCtrl.isAdded" style=""> <td/> <td> <td> <t ...

Cannot access jquery within an angular directive

I've been attempting to incorporate jquery-ui's sortable feature on the elements within an ng-repeat loop. The issue I'm facing is that I am unable to actually perform the sortable action on these ng-repeat elements. I have searched for so ...

Pausing THREE.js animations when idle

As I work on my React app using THREE.js, I find myself working with two key components: a carousel scene created in THREE.js and a full-screen overlay scene. When the overlay scene is active, I want to pause the carousel scene since it is not visible. Cu ...

TS2688 Error: Type definition file for 'tooltip.js' not found

Why am I getting an 'undefined' error when trying to import the Tooltip class from the npm tooltip.js package in my TypeScript file? ...

What is the best method for importing a single module within a monorepo project using JavaScript and NPM?

I've organized my codebase into a monorepo with the following structure: ➜ yw git:(master) tree . ├── package.json ├── packages │ ├── common │ │ ├── package.json │ │ ├── src │ │ │ ├─ ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

Troubleshooting a Simple JavaScript Game: Mastermind Edition

Currently, I am working on a JavaScript version of the well-known board game "Mastermind". I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying ...