【发布时间】:2022-11-19 16:25:34
【问题描述】:
这是我的代码。 很简单,我想知道一个元素是否在视口中。
出于某种原因,我无法理解我一直不确定。 元素存在但没有任何反应
在我看到x但从未见过q。
async function isItemInViewport( page ) {
console.log( 'x' );
await page.evaluate( () => {
console.log( 'q' );
const lastMenuItem = document.querySelectorAll( '.nav-menu--dropdown.nav-menu__container .lastitem-class-for-playwright-test' )[ 0 ].getBoundingClientRect();
console.log(lastMenuItem );
let isInViewport = false;
if (
lastMenuItem.top >= 0 &&
lastMenuItem.left >= 0 &&
lastMenuItem.bottom <= ( window.innerHeight || document.documentElement.clientHeight ) &&
lastMenuItem.right <= ( window.innerWidth || document.documentElement.clientWidth )
) {
isInViewport = true;
}
return isInViewport;
} );
}
【问题讨论】:
-
你忘了
return page.evaluate( () => {。console.log("q")从未见过,因为该代码在浏览器控制台而不是 Node 中运行。document.querySelectorAll(...)[0]很奇怪。不妨改为document.querySelector(...)。 -
谢谢,现在我得到这个错误:`page.evaluate: ReferenceError: page is not defined > 247 | return await page.evaluate( () => { 评估下有胡萝卜。`
-
取决于你如何称呼它。您是否将
page作为参数传递给isItemInViewport,并且page是有效的 Puppeteer 页面?请出示minimal reproducible example。 -
是的,我将页面作为参数传递,它是有效的,因为我在同一个测试的其他地方使用它......可能是什么问题?
-
同样,我需要看到 minimal reproducible example。如果您实际上将参数
page作为有效的 Puppeteer 页面传递,那么此处显示的代码中的任何内容都不会导致该错误。所以它是不可复制的,这意味着它无法提供帮助。
标签: playwright playwright-test