The code snippet below is an example from https://github.com/segmentio/nightmare
const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })
nightmare
.goto('https://duckduckgo.com')
.type('#search_form_input_homepage', 'github nightmare')
.click('#search_button_homepage')
.wait('#r1-0 a.result__a')
.evaluate(() => document.querySelector('#r1-0 a.result__a').href)
.end()
.then(console.log)
.catch(error => {
console.error('Search failed:', error)
})
I can't wrap my mind around this line:
.evaluate(() => document.querySelector('#r1-0 a.result__a').href)
Where does the document
come from? The code is running on Node.js, so no browser context. I've checked that the document
is not a global variable. Clearly not a parameter too. I've also verified that the example code works. How is it possible?
That arrow function is passed as a parameter to be run in the Nightmare headless browser, where document
is defined.
.evaluate(() => document.querySelector('#r1-0 a.result__a').href)
You can also pass extra arguments to this function like so:
.evaluate((arg) => {
document.querySelector('#r1-0 a.result__a').href);
}, 'test');