javascript - 如何用 Puppeteer 收听 history.pushstate?
问题描述
使用 Puppeteer,是否可以侦听浏览器历史 API,例如history.pushState
,history.replaceState
或history.popState
,通常由单页应用程序框架路由器在后台使用,例如react-router
,向后导航和第四次通过视图?
我不是在寻找page.waitForNavigation(options)
,因为它并不是真正意义上的导航,也不是听众。
此外,我希望能够捕获传递给历史函数的参数,data
例如title
和url
。
解决方案
您可以使用waitForNavigation
来监听 History API 事件。例子:
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();
根据文档,导航响应为空。“如果由于使用历史 API 而导航到不同的锚点或导航,导航将解析为 null。”
如果您使用哈希导航,您可以创建一个事件侦听器,用于当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));