Poij
Poij

Reputation: 27

Send data and user commands to running Puppeteer script

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:

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!

Upvotes: 1

Views: 1196

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13822

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

Upvotes: 1

Related Questions