首页 > 解决方案 > 如何在 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');
})

标签: node.jspuppeteer

解决方案


没有内置功能。无论如何,您都可以在这个封闭的 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";
    }

推荐阅读