18

I am tring to delete history in headless=false browser with node.js puppeteer through below code but non of method work.

await page.goto('chrome://settings/clearBrowserData');
await page.keyboard.down('Enter');

Second code

await page.keyboard.down('ControlLeft');
await page.keyboard.down('ShiftLeft');
await page.keyboard.down('Delete');
await page.keyboard.down('Enter');

i tried to used .evaluateHandle() and .click() function too but non of them work. if anyone know how to clear history with puppeteer please answer me.

Zilvia Smith
  • 511
  • 2
  • 5
  • 10

1 Answers1

38

It is not possible to navigate to the browser settings pages (chrome://...) like that.

You have three options:

  1. Use an incognito window (called context in puppeteer)
  2. Use a command from the Chrome DevTools Protocol to clear history.
  3. Restart the browser

Option 1: Use an incognito window

To clear the history (including cookies and any data), you can use an "incognito" window called BrowserContext in puppeteer.

You create a context by calling browser.createIncognitoBrowserContext(). Quote from the docs:

Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.

Example

const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();

// Execute your code
await page.goto('...');
// ...

await context.close(); // clear history

This example will create a new incognito browser window and open a page inside. From there on you can use the page handle like you normally would.

To clear any cookies or history inside, simply close the context via context.close().


Option 2: Use the Chrome DevTools Protocol to clear history

If you cannot rely on using context (as they are not supported when using extensions), you can use the Chrome DevTools Protocol to clear the history of the browser. It has functions which are not implemented in puppeteer to reset cookies and cache. You can directly use functions from the Chrome DevTools Protocol by using a CDPSession.

Example

const client = await page.target().createCDPSession();
await client.send('Network.clearBrowserCookies');
await client.send('Network.clearBrowserCache');

This will instruct the browser to clear the cookies and cache by directly calling Network.clearBrowserCookies and Network.clearBrowserCache.


Option 3: Restart the browser

If both approaches are not feasible, you can alway restart the browser, by closing the old instance and creating a new one. This will clear any stored data.

Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105