I running following code using Nightmare.js:
var test = new Nightmare()
.viewport(1000, 1000)
.useragent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36")
.goto('https://en.wikipedia.org/wiki/Ubuntu')
.inject('js', 'jquery.js')
.wait(500)
.screenshot('page.png')
.evaluate(
function ()
{
return $('h1.firstHeading').text(); //Get Heading
},
function (value)
{
console.log("Not in page context");
}
)
.run(
function (err, nightmare)
{
if (err) return console.log(err);
console.log('Done!');
}
);
The page is loaded and the screenshot, page.png, is taken correctly, but the evaluate callback never gets executed since the message "Not in page context" never gets printed. The jquery.js is in the same folder as the script and it gets successfuly injected, because if I remove the injectJS I get an error indicating that $ is not defined. I want to get the text content of the h1.firstHeading selector.
Why is the evaluate callback not executed.
The major issue lies with the fact that console.log
doesn't works in evaluate()
.
evaluate is responsible only to return the data in the callback.
Presently the evaluate function follows the format .evaluate(fn, args1, args2)
. Hence, in your case, while your first function will return data, the next one doesn't.
If you just want the heading simply return the value from the function and do a console.log(nightmare) inside the run function.
Please find the sample code changes below:
.evaluate(
function ()
{
if($('h1.firstHeading').text())
return $('h1.firstHeading').text(); //Get Heading
else
return "Not in page context";
}
)
.run(
function (err, nightmare)
{
if (err) return console.log(err);
console.log(nightmare);
console.log('Done!');
}
);
Hope this helps.! Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With