bharats
bharats

Reputation: 426

Javascript Evaluation failed: ReferenceError: parameter is not defined

I am writing a function in javascript:

const getContent = async (page, element) => {
  const contentStr = await page.evaluate(() => {
    const contentEl = document.querySelector(element);
    const content = contentEl?.getAttribute("content");

    if (content != null && content.length > 0) {
      return content;
    } else {
      return null;
    }
  });
  return contentStr;
};

When executing this function, I am getting an error:

Error: Evaluation failed: ReferenceError: element is not defined

Can anyone help?

Upvotes: 0

Views: 1995

Answers (1)

c7x43t
c7x43t

Reputation: 274

This is the function signature of puppeteer's page.evaluate

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

As you can see you can pass arguments to the pageFunction as additional paramateters when calling page.evaluate. The reason this is necessary is because one execution context ist node js while the other one is the chromium browser and those contexts run in different processes and don't share memory except when you pass variables via the puppeteer api.

So in your case this might work (not tested):

const getContent = async (page, element) => {
  const contentStr = await page.evaluate((element) => {
    const contentEl = document.querySelector(element);
    const content = contentEl?.getAttribute("content");

    if (content != null && content.length > 0) {
      return content;
    } else {
      return null;
    }
  },element);
  return contentStr;
};

Upvotes: 2

Related Questions