Search code examples
jsonxpathtypeerrorpuppeteerevaluate

Puppeteer: How to use XPath and external Variable in evaluate function?


I am trying to use an XPath and an external variable in Puppeteer's evaluate function, but there is a problem:

  • if I use the evaluate function with passing in the external variable then I can't pass in the XPath,
  • if I remove the XPath everything is fine, but I need to do it with an XPath.

I just get this error:

UnhandledPromiseRejectionWarning: 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 ()

This is my code (you can ignore the long XPath selector):

let lastNameIn = await page.$x('//*[contains(translate(@placeholder,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "LAST") and contains(translate(@placeholder,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "NAME"))]')

lastname = "test"

await page.evaluate((lastname, lastNameIn) => { 
    el => el.value = lastname, lastNameIn[0]    
}, lastname, lastNameIn)

Solution

  • You should assign only one value to el.value, then mark the element you want to evaluate at the first argument position: lastNameIn[0], as a second argument you can add the dependency variable: lastName to the pageFunction.

    See: page.evaluate, page.evaluate(pageFunction[, ...args]).

    const lastNameIn = await page.$x("...");
    const lastname = "test";
    
    await page.evaluate((el, lastname) => { 
      el.value = lastname; 
    }, lastNameIn[0], lastname);