How to listen to history.pushstate with Puppeteer?

。_饼干妹妹 提交于 2020-12-09 16:25:47

问题


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.


回答1:


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));


来源:https://stackoverflow.com/questions/52900248/how-to-listen-to-history-pushstate-with-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!