Switching between tabs with puppeteer - node.js

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

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();

In the case of clicking on a link/button to open a new tab with a new URL, the following worked for me.
await page.click('#your_Button_To_Open_New_Tab_With_Different_URL')
await page.waitForTimeout(3000)
const pageList = await browser.pages();
await console.log("NUMBER TABS:", pageList.length);
await console.log("NUMBER TABS:", pageList[2]._target._targetInfo.url);
await page.waitForTimeout(3000)
page2 = await browser.newPage()
const redirectedUrlforService = pageList[2]._target._targetInfo.url;
await page2.goto(redirectedUrlforService)
await page2.bringToFront();
await page2.waitForTimeout(3000)
await page2.waitForSelector('#A_Selector_On_New_Page_To_Verify_That_You_Can_Perform_Your_Actions_There')
Waiting for idle network requests might not always work if the responses involve long-running DOM updates that take longer than 500ms to trigger a render.

Related

Puppeteer not clicking button with text

I have a simple function that tries to accept the cookies
Here's my code:
(async () => {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://www.sport1.de/live/darts-sport');
await page.click('button[text=AKZEPTIEREN]');
// await page.screenshot({ path: 'example.png' });
// await browser.close();
})();
The cookie popup is placed in an iframe. You have to switch to iframe by contentFrame to be able to click on the accept button.
Also, if you want to filter by textContent, you need to use XPath. With CSS selector you can't get elements by its textContent.
const cookiePopUpIframeElement=await page.$("iframe[id='sp_message_iframe_373079']");
const cookiePopUpIframe=await cookiePopUpIframeElement.contentFrame();
const acceptElementToClick = await cookiePopUpIframe.$x("//button[text()='AKZEPTIEREN']");
await acceptElementToClick[0].click();

puppeteer Error: No node found for selector: .olp-text-box

I'm trying to get the number of sellers (which are selling only NEW items) on the Amazon product page using puppeteer.
for some reason, I'm getting error in the first button '.olp-text-box'.
Any ideas?
here is my code
const pupUrl = 'https://www.amazon.com/dp/' + req.body.asinIdInput;
async function configureBrowser(){
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(pupUrl , {waitUntil: 'load', timeout: 0});
await page.click('.olp-text-box');
await page.click('#aod-filter-string');
await page.click('.a-size-base.a-color-base')
return page;
}
async function checkSellers(page){
await page.reload();
let html = await page.evaluate(()=> document.body.innerHTML);
$('#aod-filter-offer-count-string',html).each(function(){
var numberOfSellers = $(this).text();
console.log(numberOfSellers);
});
}
async function monitor(){
let page = await configureBrowser();
await checkSellers(page);
}
monitor();

puppeteer overridePermissions clipboard-read not working on createIncognitoBrowserContext()

The following code is viable for reading the clipboard in headless/headfull:
var context = await client.defaultBrowserContext();
await context.overridePermissions('http://localhost', ['clipboard-read']);
page = await browser.newPage();
await page.goto( 'http://localhost/test/', {waitUntil: 'load', timeout: 35000});
// click button for clipboard..
let clipboard = await page.evaluate(`(async () => await navigator.clipboard.readText())()`);
But when you later start incognito its not working anymore:
const incognito = await client.createIncognitoBrowserContext();
page = await incognito.newPage();
and you get:
DOMException: Read permission denied.
I currently try to figure out to combine both.. Anybody know how to set overridePermissions inside of the new incognito window?
Please notice I do not want to use the incognito chrome arg at the start. I want to manually create new incognito pages inside of my scripts with correct overridePermissions.
I am having the very same issue. Here's a minimal reproducible example.
Nodejs version: v16.13.1
puppeteer version: puppeteer#14.4.1
'use strict';
const puppeteer = require('puppeteer');
const URL = 'https://google.com';
(async () => {
const browser = await puppeteer.launch();
const context = browser.defaultBrowserContext();
context.overridePermissions(URL, ['clipboard-read', 'clipboard-write'])
const page = await browser.newPage();
await page.goto(URL, {
waitUntil: 'networkidle2',
});
await page.evaluate(() => navigator.clipboard.writeText("Injected"));
const value = await page.evaluate(() => navigator.clipboard.readText());
console.log(value);
})();

Puppeteer only focus on button not clicking on button

Trying to automate the process of clicking button on website page, but it only focuses on button not clicking on it.
I have tried using puppeteer click() fucntion and focus + press enter funtion none of them working
const puppeteer = require('puppeteer');
async function run() {
const browser = await puppeteer.launch({headless:true});
const page = await browser.newPage();
const BUTTON_SELECTOR = 'body > section > section > header > div.reply-button-row > button';
await page.goto('https://bozeman.craigslist.org/zip/d/bozeman-panasonic-36-tv/6837588995.html')
await page.waitFor(2000);
await page.waitFor(BUTTON_SELECTOR);
await page.click(BUTTON_SELECTOR)
//await page.focus(BUTTON_SELECTOR)
//await page.keyboard.press('Enter');
await page.screenshot({ path: 'screenshots/image.png' });
browser.close();
}
run();
Code output image : https://imgur.com/m0CYqNiqwe
Expected Output Image : https://imgur.com/Hmg3BgVasd
It clicks, but the screenshot is made too early, till the new block is shown. You can wait some more time or wait for the block to be created and be visible:
await page.click(BUTTON_SELECTOR)
await page.waitFor(2000);
await page.screenshot({ path: 'image.png' });
or
await page.click(BUTTON_SELECTOR)
await page.waitForSelector('div.reply-info aside.reply-flap', { visible: true });
await page.screenshot({ path: 'image.png' });
Try this selector instead :
const BUTTON_SELECTOR = 'button[data-href^="/__SERVICE_ID"]'

Puppeteer: How to get DOM after switching chromium Tabs?

Right now I am getting all the DOM from Only one Tab which is Default.But I want to capture DOM from Each tab after Switching.
Here is the my sample code.
async function RedirectToLogin(page)
{
console.log(page.content());
}
async function main() {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.setViewport({
width: 2000,
height: 1000,
});
await page.goto('https://www.google.com/');
console.log('clicked');
browser.on('targetchanged', () => RedirectToLogin(page));
count++;
}
main();
You can get the URL for the currently active page by doing the following:
const url = await page.url();
console.log(url);

Resources