Home > Back-end >  node.js puppeteer "document is not defined"
node.js puppeteer "document is not defined"

Time:03-06

I am attempting to try click a button using code without an id or class, but my terminal always responds with:

document.getElementsByTagName("Accept Cookies");
    ^

ReferenceError: document is not defined

This is my code:

const puppeteer = require('puppeteer');

const product_url = "https://www.nike.com/launch"

async function givePage() {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    return page;
}

async function acceptCookies(page) {
    await page.goto(product_url);
    const btn = await page.waitForSelector('#cookie-settings-layout > div > div > div > 
div:nth-child(3) > div.ncss-col-md-6.ncss-col-sm-12.mb5-sm > button')
    await btn.click()
}

async function notifyMe(page) {
    await page.goto(product_url);
    document.querySelector("button[type=\"submit\"]").click("Notify Me");
}

async function checkout() {
    var page = await givePage();
    await acceptCookies(page);
    await notifyMe(page);
}

checkout();

What did I do wrong and how can I fix this?

CodePudding user response:

You already have an example on your code on how to access elements. Instead of document.querySelector, use page.waitForSelector like what you did on line 12.

document.querySelector('button[type="submit"]').click()

should be

(await page.waitForSelector('button[type="submit"]')).click()

CodePudding user response:

There's no built-in variable in NodeJS named document, since it doesn't run in the browser.

If you want to access document, in Puppeteer there's a page.evaluate() function where you can access the document variable (as well as everything else inside client-side JS):

// ...
await page.evaluate(() => {
  document.querySelector("button[type=\"submit\"]").click();
});

Please note though, that all the JavaScript you run will be run on the browser, not in NodeJS, so if you want to get the value back you can return:

const result = await page.evaluate(() => {
  var something = document.getElementById("something");
  return something.innerText; 
});
console.log(result); // will print in the console "blah blah blah"

Likewise if you want to pass variables to the callback you have to give them to the evaluate function:

await page.evaluate((name, age) => {
  // do something with 'name' and 'age'
}, "John", 34);

CodePudding user response:

In Nodejs, you don't have access to web APIs like a window, document, etc. so you can't use document.querySelector to select elements here.
Instead of handling clicks on DOM elements on server side, you should handle those clicks on the client-side only and then fetch the data from the server accordingly.

  • Related