Get all values from localStorage using Puppeteer

萝らか妹 提交于 2021-01-28 04:57:32

问题


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;
};

回答1:


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' ] ]


来源:https://stackoverflow.com/questions/54350526/get-all-values-from-localstorage-using-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!