javascript 如何在 puppeteer 中禁用缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48761951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I disable cache in puppeteer?
提问by Nagarjun Prasad
I want to disable cache in puppeteer, can anyone please tell me how I can do so? I found this page.setCacheEnabled(enabled)but I couldn't understand how to use the same.
我想在 puppeteer 中禁用缓存,谁能告诉我我该怎么做?我找到了这个,page.setCacheEnabled(enabled)但我不明白如何使用它。
I am aware that the browser is launched without cache or cookies but in my case the browser is always running in the background thus need a different solution.
我知道浏览器是在没有缓存或 cookie 的情况下启动的,但在我的情况下,浏览器总是在后台运行,因此需要不同的解决方案。
回答by Rippo
According to the puppeteer docs you can use await page.setCacheEnabled(enabled)
根据 puppeteer 文档,您可以使用 await page.setCacheEnabled(enabled)
This was added back in December. See Git Hub issue #1609
这是在 12 月添加的。参见 Git Hub 问题 #1609
If you look at the commit changesthere is a test e.g.
如果您查看提交更改,则有一个测试,例如
await page.goto(SOMEURL);
await page.reload({waitUntil: 'networkidle2'});
expect(responses.get('one-style.css').fromCache()).toBe(true);
await page.setCacheEnabled(false);
await page.reload({waitUntil: 'networkidle2'});
expect(responses.get('one-style.css').fromCache()).toBe(false);
回答by Grant Miller
You can use cdpSession.send()to disable cache:
您可以使用cdpSession.send()禁用缓存:
const client = await page.target().createCDPSession();
await client.send('Network.setCacheDisabled', {
cacheDisabled: true,
});
Alternatively, you can use the more readable page.setCacheEnabled():
或者,您可以使用更具可读性的page.setCacheEnabled():
await page.setCacheEnabled(false);
回答by reflog
If you want session isolation, there is also:
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
which will give you a fresh start on each page.
如果您想要会话隔离,还有:
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
这将使您在每个页面上都有一个新的开始。
回答by syam
Every browser launch starts with clean HTTP cache and without any cookies.
每次浏览器启动都以干净的 HTTP 缓存开始,没有任何 cookie。
let browser = await puppeteer.launch(); // no cache, no cookies!
You may try this. For my cases without cache , i am using this.
你可以试试这个。对于没有缓存的情况,我正在使用它。

