Puppeteer: How to handle multiple tabs?

后端 未结 8 820
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 09:09

Scenario: Web form for developer app registration with two part workflow.

Page 1: Fill out developer app details and click on button to create Application ID, which

8条回答
  •  既然无缘
    2020-12-13 09:54

    In theory, you could override the window.open function to always open "new tabs" on your current page and navigate via history.

    Your workflow would then be:

    1. Override the window.open function:

      await page.evaluateOnNewDocument(() => {
        window.open = (url) => {
          top.location = url
        }
      })
      
    2. Go to your first page and perform some actions:

      await page.goto(PAGE1_URL)
      // ... do stuff on page 1
      
    3. Navigate to your second page by clicking the button and perform some actions there:

      await page.click('#button_that_opens_page_2')
      await page.waitForNavigation()
      // ... do stuff on page 2, extract any info required on page 1
      // e.g. const handle = await page.evaluate(() => { ... })
      
    4. Return to your first page:

      await page.goBack()
      // or: await page.goto(PAGE1_URL)
      // ... do stuff on page 1, injecting info saved from page 2
      

    This approach, obviously, has its drawbacks, but I find it simplifies multi-tab navigation drastically, which is especially useful if you're running parallel jobs on multiple tabs already. Unfortunately, current API doesn't make it an easy task.

提交回复
热议问题