Rushabh Lalwani
Rushabh Lalwani

Reputation: 3

How to pass page as an argument in the function parameter of page.evaluate()?

I am getting this error when I pass page as an argument:

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>)

My corresponding code is:

const result = await page.evaluate = ( async (page, selector1, selector2) => {
    let result = [];
    const sel = document.querySelectorAll(selector1);  
    if(sel.length) {
        const total = sel.length;
        for(let i=0;i<total;i++) {
            result.push(document.querySelector(selector1 + ` div:nth-child(${i+1}) span a`).textContent);
            await page.click(selector2 + ` div:nth-child(${i+1})`);
        }
    }
    return result;       
}, page, selector1, selector2);

How do I include the page argument?

Upvotes: 0

Views: 316

Answers (1)

Rustam D9RS
Rustam D9RS

Reputation: 3491

I'm not sure if you understand how the .evaluate method works. This method executes the code in the browser context, so to click on an element, you can use such code as if you were writing it in a browser. You cannot pass complex objects like page between the browser and Node.js. I changed your code inside the .evaluate method, it should look something like this:

const result = await page.evaluate((selector1, selector2) => {
    const result = [];
    const sel = document.querySelectorAll(selector1);  
    if (sel.length) {
        const total = sel.length;
        for (let i = 0; i<total; i++) {
            result.push(sel.querySelector(`div:nth-child(${i+1})`).textContent);
            document.querySelector(`${selector2} div:nth-child(${i+1})`).click();
        }
    }
    return result;       
}, selector1, selector2);

Upvotes: 1

Related Questions