harunB10
harunB10

Reputation: 5207

Puppeteer - get input element by xpath and then click and type

I am trying to login and for this I've made the function:

async function login(page, usernameXPATH, passwordXPATH, username, password)
{
  const usernameElement = await page.$x(usernameXPATH);
  await usernameElement[0].click({clickCount: 3});
  await page.type(usernameElement[0], username);

  const passwordElement = await page.$x(passwordXPATH);
  await passwordElement[0].click({clickCount: 3});
  await page.type(passwordElement[0], password);

  await page.keyboard.press('Enter');
}

But this generates an error

TypeError: Converting circular structure to JSON
        --> starting at object with constructor 'BrowserContext'
        |     property '_browser' -> object with constructor 'Browser'
        --- property '_defaultContext' closes the circle Are you passing a nested JSHandle?
        at JSON.stringify (<anonymous>)

      at Connection._rawSend (node_modules/puppeteer/src/common/Connection.ts:100:37)
      at CDPSession.send (node_modules/puppeteer/src/common/Connection.ts:259:33)
      at ExecutionContext._evaluateInternal (node_modules/puppeteer/src/common/ExecutionContext.ts:252:44)
      at ExecutionContext.evaluateHandle (node_modules/puppeteer/src/common/ExecutionContext.ts:191:17)
      at ElementHandle.evaluateHandle (node_modules/puppeteer/src/common/JSHandle.ts:183:42)
      at Object.internalHandler.queryOne (node_modules/puppeteer/src/common/QueryHandler.ts:68:38)
      at ElementHandle.$ (node_modules/puppeteer/src/common/JSHandle.ts:778:25)
      at DOMWorld.$ (node_modules/puppeteer/src/common/DOMWorld.ts:171:34)

If I remove [0] and use just usernameElement.click() then I get an error that click() is not a function.

What am I doing wrong here?

Upvotes: 1

Views: 2473

Answers (1)

theDavidBarton
theDavidBarton

Reputation: 8871

Page.type accepts a selector as its first argument, not an element (matched by an XPath). Rather use elementHandle.type, e.g.:

async function login(page, usernameXPATH, passwordXPATH, username, password)
{
  const usernameElement = await page.$x(usernameXPATH);
  await usernameElement[0].click({clickCount: 3});
  await usernameElement[0].type(username);

  const passwordElement = await page.$x(passwordXPATH);
  await passwordElement[0].click({clickCount: 3});
  await passwordElement[0].type(password);

  await page.keyboard.press('Enter');
}

Upvotes: 1

Related Questions