How to handle pop-ups in a puppeteer

how to handle the popup and access the popup to perform some operations on it.

const puppeteer = require('puppeteer'); async function run() { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await page.click(Launchpopup); } 
+11
source share
4 answers

Starting with version 0.13.0, you can use the following code:

 ... code to open popup... const pages = await browser.pages(); // get all open pages by the browser const popup = pages[pages.length - 1]; // the popup should be the last page opened 
+3
source

This Typescript code, but you get the idea:

 async function waitForPopupMatching( browser: Puppeteer.Browser, regex: RegExp, openAction: () => Promise<void>, timeout: number = 30000, ): Promise<Puppeteer.Page> { const promise = new Bluebird<Puppeteer.Target>(resolve => { const listener = async (target: Puppeteer.Target) => { if (target.type() === 'page' && regex.test(target.url())) { browser.removeListener('targetcreated', listener); resolve(target); } }; browser.addListener('targetcreated', listener); }).timeout(timeout); await openAction(); // Typically a mouse click const tgt = await promise; return await tgt.page(); } 
+3
source

So what I do is go to Facebook on their homepage, then go to the page I want to go to, where I click on it to enter using the facebook button. And then this code below will be, when the popup occurs, click on the Facebook login button.

  await page.click('[service_name="facebook"]') const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page()))); const popup = await newPagePromise; await popup.waitForSelector('[name="__CONFIRM__"]') const confirm = await popup.$('[name="__CONFIRM__"]') await popup.click('[name="__CONFIRM__"]') await page.waitFor(2000); await page.goto('your login page'); $ 
+1
source

You should check the documentation for v0.12.0-alpha, it describes how to interact with dialogs.

 const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { const page = await browser.newPage(); await page.goto('https://example.com'); page.on('dialog', async dialog => { console.log(dialog.message()); await dialog.dismiss(); await browser.close(); }); page.evaluate(() => alert('1')); }); 

Relevant docs can be found here .

0
source

Source: https://habr.com/ru/post/1272502/


All Articles