如何用Puppeteer收听history.pushstate? [英] How to listen to history.pushstate with Puppeteer?

查看:35
本文介绍了如何用Puppeteer收听history.pushstate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Puppeteer,可以收听浏览器历史记录API,例如 history.pushState history.replaceState history.popState ,经常被单页应用程序框架的路由器(例如 react-router )在后台使用,以在视图之间来回导航?
我不是在寻找 page.waitForNavigation(options),因为它并不是真正意义上的导航,也不是听众.
此外,我希望能够捕获传递给历史函数的参数,例如 data title url .

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.

推荐答案

您可以使用 waitForNavigation 来监听History API事件.示例:

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

根据文档,导航响应为null.如果使用History API导航到其他锚点或导航,导航将以null解析."

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

这篇关于如何用Puppeteer收听history.pushstate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆