等待过渡以 puppeteer 结束 [英] Wait for transition to end in puppeteer

查看:71
本文介绍了等待过渡以 puppeteer 结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Puppeteer 测试网站.不幸的是,我无法单击工具栏中的元素.工具栏使用 CSS 过渡优雅地滑入页面.我的代码失败,因为我在页面仍在动画时单击元素将出现的位置.我使用超时作为解决方法,但必须有一个更优雅的解决方案.举个例子:

I'm trying to test a website using Puppeteer. Unfortunately, I'm having trouble clicking elements in a toolbar. The toolbar is using a CSS transition to gracefully slide into the page. My code is failing because I'm clicking where the element will appear while the page is still animating. I'm using a timeout as a workaround, but there's got to be a more elegant solution. Here's an example:

await page.click("#showMeetings"); //Toolbar slides in
await page.waitFor(3000); //Can I do this without a timeout?
await page.click("#mtgfind"); //Click button in toolbar

我想我需要等待 transitionend 事件,但我不确定如何在 Puppeteer 中做到这一点.任何帮助将不胜感激.

I think I need to wait on the transitionend event, but I'm unsure of how to do that in Puppeteer. Any help would be appreciated.

推荐答案

在 Grant 解决方案的情况下,您不应该忘记移除事件侦听器并等待它.你可以试试这个解决方案,它对我有用.我遇到了类似的问题.

In case of Grant solution, you shouldn't forget to remove event listener and to wait for it. You can try this solution, it works for me. I had similar problem.

async waitForTransitionEnd(element) {
  await page.evaluate((element) => {
    return new Promise((resolve) => {
      const transition = document.querySelector(element);
      const onEnd = function () {
        transition.removeEventListener('transitionend', onEnd);
        resolve();
      };
      transition.addEventListener('transitionend', onEnd);
    });
  }, element);
}

并调用它:

await page.click('#showMeetings');
await waitForTransitionEnd('#elementWithTransition');
await page.click("#mtgfind");

这篇关于等待过渡以 puppeteer 结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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