4

Using Puppeteer, is it possible to listen to the browser history API such as history.pushState, history.replaceState or history.popState, often used under the hood by single page application frameworks routers, like react-router, to navigate back and fourth through views?
I'm not looking for page.waitForNavigation(options), as it's not really navigating in the literal sense of the word, and is not a listener.
Moreover, I would like to be able to capture the arguments passed to history functions, such as data, title and url.

  • [FAQ of Puppeteer](https://developers.google.com/web/tools/puppeteer/faq) says the following: `From Puppeteer’s standpoint, “navigation” is anything that changes a page’s URL. Aside from regular navigation where the browser hits the network to fetch a new document from the web server, this includes anchor navigations and History API usage.` So you should be able to use `page.waitForNavigation(options)` for History API events also – Volodymyr Oct 19 '18 at 22:04
  • Does not work with `react-router`, this throws a timeout error... –  Oct 19 '18 at 22:55
  • Does this answer your question? [puppeteer: How to wait for pages in SPA's?](https://stackoverflow.com/questions/49490100/puppeteer-how-to-wait-for-pages-in-spas) – ggorlen Nov 10 '20 at 02:46

1 Answers1

5

You can use waitForNavigation to listen for History API events. Example:

const browser = await puppeteer.launch();
const page = await browser.newPage();

await page.goto('https://www.google.com');

const [navResponse] = await Promise.all([
    page.waitForNavigation(),
    page.evaluate(() => { history.pushState(null, null, 'imghp') }),
])

console.log(navResponse) // null as per puppeteer docs
await browser.close();

As per the documentation, the navigation response is null. "In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null."

If you are using hash navigation, you can create an event listener for when the route changes as specified in the puppeteer-examples.

  await page.exposeFunction('onHashChange', url => page.emit('hashchange', url));
  await page.evaluateOnNewDocument(() => {
    addEventListener('hashchange', e => onHashChange(location.href));
  });

  // Listen for hashchange events in node Puppeteer code.
  page.on('hashchange', url => console.log('hashchange event:', new URL(url).hash));
Matt Shirley
  • 4,216
  • 1
  • 15
  • 19
  • With `react-router`, `page.waitForNavigation()` will just end up in _TimeoutError: Navigation Timeout Exceeded_ –  Oct 19 '18 at 22:54
  • 2
    I thought this was resolved in https://github.com/GoogleChrome/puppeteer/commit/fafd156d7bd9941131ab31f5af7cf047e728142c - I've updated my answer to include how to listen for hash navigation changes. – Matt Shirley Oct 19 '18 at 23:06