使用Puppeteer,是否可以监听浏览器历史记录API,例如history.pushState
, history.replaceState
or history.popState
,通常由单页应用程序框架路由器在幕后使用,例如react-router
,通过视图向后和第四导航?
我不是在寻找page.waitForNavigation(options)
,因为它并不是真正意义上的导航,也不是听众。
此外,我希望能够捕获传递给历史函数的参数,例如data
, title
and 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。”
如果您使用散列导航,则可以创建一个事件侦听器,以便在路由按照指定的方式更改时创建事件侦听器。傀儡师示例.
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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)