我们有一些路由逻辑,如果你没有JWT_TOKEN设置,它会把你踢到主页……我想在页面加载之前/在调用js之前设置它。
我该怎么做呢?
发布于 2018-08-11 21:08:52
您必须像这样注册localStorage
项目:
await page.evaluate(() => {
localStorage.setItem('token', 'example-token');
});
您应该在页面page.goto
之后执行此操作-浏览器必须有一个url才能在其上注册本地存储项目。在此之后,再次进入同一页面,这个时间令牌应该在页面加载之前就在这里。
下面是一个完整的工作示例:
const puppeteer = require('puppeteer');
const http = require('http');
const html = `
<html>
<body>
<div id="element"></div>
<script>
document.getElementById('element').innerHTML =
localStorage.getItem('token') ? 'signed' : 'not signed';
</script>
</body>
</html>`;
http
.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(html);
res.end();
})
.listen(8080);
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://localhost:8080/');
await page.evaluate(() => {
localStorage.setItem('token', 'example-token');
});
await page.goto('http://localhost:8080/');
const text = await page.evaluate(
() => document.querySelector('#element').textContent
);
console.log(text);
await browser.close();
process.exit(0);
})();
发布于 2019-05-15 11:06:01
在Puppeteer's GitHub issues中有一些关于这方面的讨论。
您可以在域中加载页,设置localStorage,然后使用localStorage ready转到您想要加载的实际页面。你也可以截取第一个url加载后立即返回,而不是实际加载页面,这可能会节省很多时间。
const doSomePuppeteerThings = async () => {
const url = 'http://example.com/';
const browser = await puppeteer.launch();
const localStorage = { storageKey: 'storageValue' };
setDomainLocalStorage(browser, url, localStorage);
const page = await browser.newPage();
// do your actual puppeteer things now
};
const setDomainLocalStorage = async (browser, url, values) => {
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', r => {
r.respond({
status: 200,
contentType: 'text/plain',
body: 'tweak me.',
});
});
await page.goto(url);
await page.evaluate(values => {
for (const key in values) {
localStorage.setItem(key, values[key]);
}
}, values);
await page.close();
};
发布于 2020-03-06 22:37:22
在不需要双倍goTo
的情况下,这是可行的:
const browser = await puppeteer.launch();
browser.on('targetchanged', async (target) => {
const targetPage = await target.page();
const client = await targetPage.target().createCDPSession();
await client.send('Runtime.evaluate', {
expression: `localStorage.setItem('hello', 'world')`,
});
});
// newPage, goTo, etc...
改编自灯塔文档,适用于做类似事情的木偶师:https://github.com/GoogleChrome/lighthouse/blob/master/docs/puppeteer.md
https://stackoverflow.com/questions/51789038
复制相似问题