2

I want to make Puppeteer click on some tabs based on the number of items in an array called tabs:

;(async () => {
  const browser = await puppeteer.launch({
    headless: true
  })   

  const page = await browser.newPage()
  await page.goto(`https://www.example.com`)

  const tabs = ['tab1', 'tab2', 'tab3']

  tabs.forEach((tab, index) => {
    await page.click(`.postab-container li:nth-of-type(${ index + 1 }) a`)
  })
})()

But I get this error:

await page.click(`.postab-container li:nth-of-type(${ index + 1 }) a`)
      ^^^^

SyntaxError: Unexpected identifier

It seems like the forEach statement is messing up page.

What's the correct way of doing this?

alexchenco
  • 53,565
  • 76
  • 241
  • 413

1 Answers1

6

The function inside of the forEach is not an async function so you cannot use await, but even if you changed it to an async function you would not get the result you anticipate (forEach will generate all the requests at once, and not await each async function). Use a for loop instead.

  for(let index =0;index<tabs.length;++index){
    let tab = tabs[index];
    await page.click(`.postab-container li:nth-of-type(${ index + 1 }) a`)
  }
Cody G
  • 8,368
  • 2
  • 35
  • 50