Royi Namir
Royi Namir

Reputation: 148744

Return a complex object from page.evaluate using puppeteer?

I was asked to create a task that clicks random links on a website ( in order to test something).

So I have something like this :

 await page.evaluate((a, shuf) =>
                                {
                                  function shuffle(array)
                                   {
                                     //...
                                     return array;
                                   }

    //let's get the first one
    let anchor = shuffle([...document.querySelectorAll('a')].filter(...)[0];

    (anchor).click();

 });

1) Notice that I had to inline the shuffle function , because otherwise , it doesn't know it. Is there any way to put this function outside page.evaluate , and "send" it to the evaluate function ?

2) I don't want to click the anchor ((anchor).click();) it in the evaluate function. I want to return the DOM object of anchor and to do some other manipulations then click it. The problem is that a DOM is a complex object which is not serialized , so I can't return it. Is there any way to do a workaround for this ?

Upvotes: 0

Views: 483

Answers (1)

pguardiario
pguardiario

Reputation: 55002

1) You need to add shuffle() to the browser context:

await page.evaluate(() => {
  window.shuffle = array => {
    return array.reverse()
  }
})

Now you can use it in evaluate:

let shuffled = await page.evaluate((array) => window.shuffle(array), [1,2,3,4,5])

2) Maybe something like this?

await page.evaluate(() => {
  window.anchors = [...document.querySelectorAll('a[href]')]
  return 'something else'
})

await page.evaluate(() => {
  window.anchors[0].click()
})

Upvotes: 1

Related Questions