Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching between tabs with puppeteer

I need a example how to switch betweens tabs with puppeteer

this is currently what i have:

const puppeteer = require('puppeteer');



(async () => {
    const browser = await puppeteer.launch({
    headless: false, // launch headful mode
});


    const page = await browser.newPage();
    await page.setViewport({ width: 1920, height: 1080 });
                await page.goto('https://URL1.com');




    const pagee = await browser.newPage();
    await pagee.setViewport({ width: 1920, height: 1080 });
                await pagee.goto('https://URL2.com');

})();

So it opens 2 tabs first:Url1, second: Url2

What i need:

first Tab do some action... go to second Tab do some action... go back to first Tab do some action...

can you guys please provide me a example ?

thank you

like image 747
N.oelN Avatar asked Feb 01 '18 13:02

N.oelN


People also ask

Does puppeteer support multiple tabs?

Both Puppeteer and Playwright enable us to control multiple browser tabs, albeit in different ways.

How do I get a puppeteer to open in a new tab?

You open a new tab in puppeteer using the newPage() method present in the browser object. const page = await browser. newPage(); Complete code for opening the new tab in the browser.

How do you click a link on a puppeteer?

Puppeteer is capable of handling a link/button on a page. Before clicking an element we must be able to uniquely identify it with the help of any of the locators. In Puppeteer, we can click an element only if its dimensions are greater than zero pixel.


Video Answer


1 Answers

The bit of code you need is page.bringToFront See here

A working script below. Please note I have adding in a wait between tab switching else the script runs to fast :)

const puppeteer = require('puppeteer'); 

async function run() {
    const browser = await puppeteer.launch( {
        headless: false
    }); 

    const page1 = await browser.newPage(); 
    await page1.goto('https://www.google.com');

    const page2 = await browser.newPage(); 
    await page2.goto('https://www.bing.com');

    const pageList = await browser.pages();    
    console.log("NUMBER TABS:", pageList.length);

    //switch tabs here
    await page1.bringToFront();
    blockingWait(1);
    await page2.bringToFront();
    blockingWait(1);
    await page1.bringToFront();
    blockingWait(4);

    await browser.close(); 
}; 

function blockingWait(seconds) {
    //simple blocking technique (wait...)
    var waitTill = new Date(new Date().getTime() + seconds * 1000);
    while(waitTill > new Date()){}

}

run(); 
like image 109
Rippo Avatar answered Nov 15 '22 07:11

Rippo