4 javascript ecmascript-6 puppeteer
使用 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();
Run Code Online (Sandbox Code Playgroud)
根据文档,导航响应为空。“如果由于 History 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));
Run Code Online (Sandbox Code Playgroud)