使用Puppeteer从localStorage获取所有值 [英] Get all values from localStorage using Puppeteer
本文介绍了使用Puppeteer从localStorage获取所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用Puppeteer从 localStorage
中获取所有值?包括来自第三方域的值(假设我不知道所有第三方域).
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).
我正在寻找与此类似的东西,它可以从浏览器中获取所有cookie(但用于 localStorage
).
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;
};
推荐答案
但是,如果我们假设localStorage origins =帧,则可以通过以下两种方式之一获取数据:
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' ] ]
这篇关于使用Puppeteer从localStorage获取所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文