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
Both Puppeteer and Playwright enable us to control multiple browser tabs, albeit in different ways.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With