How to set a global variable in Browser scope .wait(fn) NightmareJS

I want to set a global variable based on the web I am scraping. However, I was able to do this only with .evaluate and .then. This is not what I need, because I wasn’t able to run anything after that.

Thanks for the Help! 🙂

var global;

nightmare
.goto(url)
.wait(() => {
  global = document.getElementById("element").textContent;
})
.click()
.wait()
.more...

Answer

People will tell you not to do things with global variables. I guess you just want to store and use some data in some small script. There are several ways to save the variable for later use. I won’t go thru database and stuff like that for now.

Window Object inside the Nightmare instance

You can use window object since it will be there as long as you are same page and don’t refresh the page.

await nightmare
.goto(url)
.evaluate(() => {
  window.aGlobalVariable = document.getElementById("element").textContent;
})

and then later you can call it later as long you are in same page.

await nightmare
.evaluate(() => {
  console.log(`${aGlobalVariable} looks tasty`);
})

Saving and passing the variable between contexts

let aGlobalVariable;
aGlobalVariable = await nightmare
.goto(url)
.evaluate(() => {
  return document.getElementById("element").textContent;
})

Now you can access aGlobalVariable from the nodeJS context. Whenever you want it inside nightmareJS again, you can pass it to the browser again if you want.

await nightmare
.goto(url)
.evaluate((aGlobalVariable) => { // <-- call it in the function
  console.log(`${aGlobalVariable} looks tasty.`)
}, aGlobalVariable) // <-- pass it here

Make sure you know about async await and promises, otherwise you will end up getting weird errors when running these codes.

Here are some references for that.

Leave a Reply

Your email address will not be published. Required fields are marked *