Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values from localStorage using Puppeteer

Is it possible to get all the values from localStorage using Puppeteer? including values from third-party domains (with the assumption that I don't know all the third-party domains).

I am looking for something similar with this, which gets all the cookies from the browser (but for localStorage).

export const getCookies = async page => {
  const { cookies } = await page._client.send("Network.getAllCookies", {});

  return cookies;
};
like image 279
Vitalie Maldur Avatar asked Nov 02 '25 20:11

Vitalie Maldur


1 Answers

However, if we suppose that localStorage origins = frames, we can get the data by any of these two ways:

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();

    await page.goto('https://example.org/');


    await page.evaluate(() => {
      document.body.appendChild(document.createElement('iframe')).src = 'https://example.net/';
      document.body.appendChild(document.createElement('iframe')).src = 'https://example.com/';
    });

    for (const frame of page.frames()) {
      await frame.waitForSelector('head > title');
      await frame.evaluate(() => {
        localStorage.setItem('foo', document.location.href);
        localStorage.setItem('bar', document.title);
      });
    }

    const client = await page.target().createCDPSession();
    for (const frame of page.frames()) {
      const securityOrigin = new URL(frame.url()).origin;
      const response = await client.send(
        'DOMStorage.getDOMStorageItems',
        { storageId: { isLocalStorage: true, securityOrigin } },
      );
      console.log(response.entries);
    }

    console.log('----------');

    for (const frame of page.frames()) {
      const entries = await frame.evaluate(() => {
        const data = [];
        for (var i = 0; i < localStorage.length; i++) {
          const key = localStorage.key(i);
          data[i] = [key, localStorage.getItem(key)];
        }
        return data;
      });
      console.log(entries);
    }

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();
[ [ 'foo', 'https://example.org/' ],
  [ 'bar', 'Example Domain' ] ]
[ [ 'foo', 'https://example.net/' ],
  [ 'bar', 'Example Domain' ] ]
[ [ 'foo', 'https://example.com/' ],
  [ 'bar', 'Example Domain' ] ]
----------
[ [ 'foo', 'https://example.org/' ],
  [ 'bar', 'Example Domain' ] ]
[ [ 'foo', 'https://example.net/' ],
  [ 'bar', 'Example Domain' ] ]
[ [ 'foo', 'https://example.com/' ],
  [ 'bar', 'Example Domain' ] ]
like image 169
vsemozhebuty Avatar answered Nov 04 '25 09:11

vsemozhebuty