So, I have a function that returning page
that needed by next function:
async function browser(){
const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox'], headless: false, devtools : true});
const incog = await browser.createIncognitoBrowserContext();
const page = await incog.newPage();
await page.goto('web')
.then(function(){
page.evaluate(function(){
$(document).ready(function(){
$('input[name ="username"]').val("a");
$('input[name ="password"]').val("b");
$(document).ready(function(){
$('#loginbtn').click();
});
});
});
});
await page.waitForNavigation({waitUntil : 'load'});
return page;
So, I pass the result value browser()
by doing
browser().then(result => nextFunction(result)
that eventually passing page into nextFunction()
async function nextFunction(page){
await page.goto('web')
.then(function(){
var msg = "Test : \n\n";
page.evaluate(function(){
var num = 1;
$('.card').each(function(i, e){
msg += "======= Activity "+num+" ========\n";
msg += "Subject : " + $(this).find('.name').text() + "\n";
msg += "Due : " + $(this).find('.date').text() + "\n";
msg += "===== End Activity "+num+" ======\n\n";
num++;
});
});
console.log(msg);
});
}
I tried to print msg
from nextFunction()
, but it only print Test:
What am I try to achieve is :
Get msg
result or assign variable from return value of nextFunction()
Is there any solution or better way to do this?
then
. Using both makes the code difficult to read. async/await is more readable and less tricky for error handling. Read more here console.log
in evaluate
, listen on 'console' event:const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
page.evaluate
context is separate from Puppeteer, so evaluate's msg
will be undefined
. Move the msg
to evaluate and then return the result back to puppeteer.let msg = await page.evaluate(function(){
let msg = "Test : \n\n";
let num = 1;
$('.card').each(function(i, e){
msg += "======= Activity "+num+" ========\n";
msg += "Subject : " + $(this).find('.name').text() + "\n";
msg += "Due : " + $(this).find('.date').text() + "\n";
msg += "===== End Activity "+num+" ======\n\n";
num++;
});
return msg;
});