0

How do I pass additional variables into a page.on('dialog') function?

How do I get the return from the function?

page.on('dialog', async (dialog) => {
  console('get additional variables:', param) // get additional variables
  if (dialog.message() === param) {
    res.isSuccess = true;
    await dialog.accept();
  }
  else {
    res.isSuccess = false;
    await dialog.accept();
  }
}, p);

console('get return:', res) // Need to get res.isSuccess
ggorlen
  • 44,755
  • 7
  • 76
  • 106
zc g
  • 3
  • 2
  • Does this answer your question? [Puppeteer not picking up dialog box](https://stackoverflow.com/questions/68585704/puppeteer-not-picking-up-dialog-box) – ggorlen Oct 28 '21 at 14:25

1 Answers1

0

I assume you need to intercept the first dialog event. Otherwise isSuccess loses any logical meaning. The interception needs to be performed in a synchronized manner to allow for a testing logic.

Promises are a good solution in your case.

Opt 1 - Wrap in promise and test

function dialog(inputValue) {
    return new Promise((resolve, reject) => {
        page.once('dialog', async dialog => {
            console.log('additional', inputValue);
            if (dialog.message() === inputValue) {
                await dialog.accept();
                resolve();
            } else {
                await dialog.accept();
                reject();
            }
        });
    })
}

Then in your code, you can use it like:

try {
    await dialog('Some message');
    console.log('OK');
} catch (e) {
    console.log('ERROR');
}

Opt 2 - Create a promise

Create a promise wrapper that intercepts the first dialog and returns it:

function firstDialog() {
    return new Promise(resolve => {
        page.once('dialog', async dialog => {
            await dialog.accept();
            resolve(dialog);
        });
    })
}

Then in your code simply test whatever you need:

const dialog = await firstDialog();
if (dialog.message() === 'Some message') {
    console.log('OK');
} else {
    console.log('ERROR');
}

Code has not been tested, minor changes may be required

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Newbie
  • 4,462
  • 11
  • 23