node.js - 如何在 Puppeteer 中获取当前页面?
问题描述
如何获取当前页面的 url?
用途:通过Gmail客户端登录
(async () => {
const browser = await puppeteer.launch({headless:false, slowMo:50});
const page = await browser.newPage();
await page.goto('https://my.gumtree.com/login', {waitUntil: 'networkidle2'});
//click on Google Sign In button
const myButton = await page.$('#google-sign-in-button');
myButton.click();
//wait for the pop up window to load
const nav1 = new Promise(res => browser.on('targetcreated', res))
await nav1
const pages = await browser.pages();
const secondPage = pages[2];
await secondPage.focus('input[type=email]')
await secondPage.keyboard.type('someValidEmail@gmail.com')
customButton = await secondPage.$('span.VfPpkd-vQzf8d');
customButton.click()
//Everything works as expected until here
await page.waitForNavigation()
** 如何获取当前页面 url?应该在索引 3 **
const allPages = await browser.pages();
// console.log("0 " + allPages[0].url());
// console.log("1 " + allPages[1].url());
// console.log("2 " + allPages[2].url());
// console.log("3 " + allPages[3].url()); //prints undefined, this should be the top page
prints:
0 about:blank
1 https://my.gumtree.com/login
2 https://accounts.google.com/o/oauth2/auth/identifier?redirect_uri=storagerelay%3A%2F%2Fhttps%2Fmy.gumtree.com%3Fid%3Dauth500948&response_type=permission%20id_token&scope=email%20profile%20openid&openid.realm&client_id=67555700125-lvoarr4qau5lkhuks3bn3bl9u3bmmfuf.apps.googleusercontent.com&ss_domain=https%3A%2F%2Fmy.gumtree.com&fetch_basic_profile=true&gsiwebsdk=2&flowName=GeneralOAuthFlow
the message is Cannot read property 'url' of undefined
//await browser.close();
})().catch((error) =>{
console.error(error.message)
});
app.listen(3000, function (){
console.log('server started');
})
解决方案
没有内置功能。无论如何,您都可以在这个封闭的 puppeteer github 问题上找到解决方案 https://github.com/puppeteer/puppeteer/issues/443#issuecomment-423440720
async function getActivePage(browser, timeout) {
var start = new Date().getTime();
while(new Date().getTime() - start < timeout) {
var pages = await browser.pages();
var arr = [];
for (const p of pages) {
if(await p.evaluate(() => { return document.visibilityState == 'visible' })) {
arr.push(p);
}
}
if(arr.length == 1) return arr[0];
}
throw "Unable to get active page";
}
推荐阅读
- memory-management - 提供给跟踪驱动模拟器的跟踪输入是什么样的?
- react-native - 全新安装时的expo-cli错误
- c# - 从 .Net Core 3.1 调用 WCF BasicBinding 服务
- datatables - 数据表/多选组件 - 选择过滤器“字母”顺序
- python - NAType 对象不可调用错误 - 对浮点数求和
- docusignapi - DocuSign API - C# 控制台应用程序 - RequestJWTUserToken - 错误“consent_required”
- colors - 如何更改引导加载程序的颜色
- python - PyQt5中的Tkinter窗口、按钮和显示HTML页面
- html - 通过输入/输出在 HTML 中显示常量?
- jquery - 未捕获的错误:语法错误,来自 1.7.1js 的 jQuery 1.12.4 中无法识别的表达式