Puppeteer: How to handle multiple tabs?

后端 未结 8 797
爱一瞬间的悲伤
爱一瞬间的悲伤 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:52

    it looks like there's a simple 'page.popup' event

    Page corresponding to "popup" window Emitted when the page opens a new tab or window.

    const [popup] = await Promise.all([
      new Promise(resolve => page.once('popup', resolve)),
      page.click('a[target=_blank]'),
    ]);
    const [popup] = await Promise.all([
      new Promise(resolve => page.once('popup', resolve)),
      page.evaluate(() => window.open('https://example.com')),
    ]);
    

    credit to this github issue for easier 'targetcreated'

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题