如何使用 Puppeteer 收听 history.pushstate?

4 javascript ecmascript-6 puppeteer

使用 Puppeteer,是否可以收听浏览器历史 API,例如history.pushStatehistory.replaceStatehistory.popState,通常由单页应用程序框架路由器react-router在后台使用,例如,通过视图来回导航?
我不是在寻找page.waitForNavigation(options),因为它并不是真正意义上的导航,也不是倾听者。
此外,我希望能够捕获传递给历史函数的参数,例如data,titleurl

Mat*_*ley 5

您可以使用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)

  • 我认为这已在 https://github.com/GoogleChrome/puppeteer/commit/fafd156d7bd9941131ab31f5af7cf047e728142c 中解决 - 我已经更新了我的答案以包括如何侦听哈希导航更改。 (2认同)