我正在尝试将localStorage保存到page.evaluate()之外的变量中。但似乎我做不到。下面是我试图使用consloe.log()的代码和输出,我如何使其工作并将localStorage保存为变量?在回调内部,我可以看到localStorage,但是由于getItem无法正常工作,它无法正常工作。
我正在尝试几种方法来获取数据,但似乎都无法正常工作...知道为什么吗?
await page.click("[id=Login-button]");
let savedLocalStorage = "";
const result = await page.evaluate(savedLocalStorage => {
console.log(localStorage); //output: {AUTH: 12345}
console.log(localStorage.key(0)); //output: null
console.log(localStorage.getItem("AUTH")); //output: null
localStorage.setItem("Test", "1234"); //working
console.log(localStorage); //output: {AUTH: 12345, Test: 1234}
savedLocalStorage = localStorage;
//savedLocalStorage = localStorage.AUTH; - same result as savedLocalStorage = localStorage;
return localStorage;
}, savedLocalStorage);
console.log(savedLocalStorage); //output: ""
console.log(result); //output: {}
答案 0 :(得分:0)
尝试序列化数据,
async function saveLocalStorage(page, filePath) {
const json = await page.evaluate(() => {
const json = {};
for (const i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
json[key] = localStorage.getItem(key);
}
return json;
});
fs.writeFileSync(filePath, 'utf8', JSON.stringify(json));
}
async function restoreLocalStorage(page, filePath) {
const json = JSON.parse(fs.readFileSync(filePath, 'utf8'));
await page.evaluate(json => {
localStorage.clear();
for (let key in json)
localStorage.setItem(key, json[key]);
}, json);
}
答案 1 :(得分:0)
首先,您将无法通过savedLocalStorage
作为参考。 evaluate
中的脚本将获得该变量的序列化副本。
关于result
。 Puppetter不会返回序列化的localStorage,而是返回指向浏览器内部对象的指针(JSHandle)。基本上,它是一个伪造的对象,您可以将其传递给另一个evaluate
函数,在本例中为“作为参考”。
您可以做的是序列化localStorage,然后在另一端进行解析。
const result = await page.evaluate(() => {
localStorage.setItem("Test", "1234"); //working
return JSON.stringify(localStorage);
});
console.log(JSON.parse(result));
<!DOCTYPE html>
<html>
<head>
<title>console.log test</title>
</head>
<body>
<script>
localStorage.setItem("AUTH", 12345);
</script>
</body>
</html>