Search code examples
javascriptnode.jsasync-awaitpuppeteerheadless

node.js puppeteer evaluate() returning Unexpected objects. throws TypeError each time


I Cannot understand why the following code complains check() is not a function. when i make it an object with the target function it again complains that no such function is found. I have tried to resolve this problem for like 6 hours now. any help will be appreciated...

 const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto('https://bet254.com');

 const check=await page.evaluate(() => {
            return function () {
            try {
                return document.getElementsByClassName("header-buttons")[0].childNodes[0].textContent.trim() !== "Login";
            } catch (e) {
                console.log(e);
                return false;
            }
        }
 });
if (check()) {
        console.log("Logged in already!");
    } else {}

The following is the error:-

(node:9632) UnhandledPromiseRejectionWarning: TypeError: check is not a function
    at D:\void\js_\node_puppeteer\entry.js:19:9
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:9632) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9632) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


Solution

  • Unfortunately, page.evaluate() can only transfer serializable values (roughly, the values JSON can handle). Functions are not serializable. So you can try, for example, one of these ways:

    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto('https://bet254.com');
    
    const check = await page.evaluate(() => {
        return document.getElementsByClassName("header-buttons")[0].childNodes[0].textContent.trim() !== "Login";
    });
    
    if (check) {
        console.log("Logged in already!");
    } else {}
    
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto('https://bet254.com');
    
    function check(page) {
      return page.evaluate(() => {
          return document.getElementsByClassName("header-buttons")[0].childNodes[0].textContent.trim() !== "Login";
      });
    }
    
    if (await check(page)) {
        console.log("Logged in already!");
    } else {}