1

I'm new to Puppeteer and have few problems with it.

Generally, I want to control the script with user input, e.g while the script is running tell it to change page or print element's contents. It will look like this:

  • Run puppeteer script, open browser and page
  • Let page do what it's doing
  • Wait for user input e.g: [ >> changePage example.com ]
  • Parse and execute user command e.g: [ await page.goto('example.com') ]

Here's what I'm trying to achieve, code below is just a pseudo-code.

const puppeteer = require('puppeteer');
const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin
});

function parse_user_input(user_str)  // executes user commands
{
  user_args = user_str.split(' ');
  if (user_args[0] == "changePage")
  {
    await page.goto(user_args[1]);
  }
}

function get_user_input()  // returns user input
{
  return rl.question('>> ');
}

(async() => {

  // code for opening the browser and page (already written)

  while (true)  // I don't want to block the running page
  {             // (in real code this gets wild and doesn't wait for input)
     user_str = get_user_input();
     parse_user_input(user_str);
  }

});

Thanks for all your suggestions!

1 Answer 1

1

Can this template be of any help?

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

function getInput(question) {
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      resolve(answer);
    });
  });
}

(async function main() {
  try {
    while (true) {
      const input = await getInput('Enter a command: ');
      console.log(`Entered command: ${input}`);
      if (input === 'break') break;
    }
    rl.close();
  } catch (err) {
    console.error(err);
  }
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much :) That's exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.