What is the Puppeteer equivalent of window.localStorage?
Ava W
ava w profile pic

The Puppeteer equivalent ofwindow.localStorage is thepage.evaluate() method in conjunction with thelocalStorage object. Here's a detailed explanation of how to access and interact with local storage in Puppeteer: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Accessing local storage usingpage.evaluate(): To access or interact with local storage in Puppeteer, you can usepage.evaluate() to execute JavaScript code within the page context and access thelocalStorage object.

1
2
3
4
5
6

   const localStorageData = await page.evaluate(() => {
     return localStorage.getItem('your-key');
   });
   console.log(localStorageData);
   

In this example,page.evaluate() is used to execute JavaScript code within the page context. The evaluated code retrieves the value associated with the specified key fromlocalStorage. The returned value is assigned to thelocalStorageData variable, which can then be used or displayed as needed. 3. Modifying local storage data usingpage.evaluate(): You can also modify the local storage data by calling appropriate methods on thelocalStorage object withinpage.evaluate().

1
2
3
4
5

   await page.evaluate(() => {
     localStorage.setItem('your-key', 'your-value');
   });
   

In this code snippet,localStorage.setItem() is used to set a value in local storage. Adjust the key and value as per your requirements. 4. Clearing local storage: To clear the entire local storage, you can usepage.evaluate() to execute JavaScript code that clears the storage.

1
2
3
4
5

   await page.evaluate(() => {
     localStorage.clear();
   });
   

This code snippet clears the entire local storage by callinglocalStorage.clear() withinpage.evaluate(). By following these steps, you can access and interact with local storage in Puppeteer. Usingpage.evaluate() allows you to execute JavaScript code within the page context and access thelocalStorage object. You can retrieve values, modify data, or clear the entire local storage as needed. This enables you to work with local storage just like you would in a regular browser environment.