Nightmare Js evaluate page
Asked Answered
O

1

5

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.

Olva answered 11/11, 2015 at 20:44 Comment(1)
.evaluate is meant to run under browser's context not in node's context which is why you don't see it being outputted. As @Aditya, mentioned you can return values from browser context to node's context and check it that way.Cynthiacynthie
N
7

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

Nammu answered 13/11, 2015 at 6:5 Comment(1)
How do you work with multiple evaluate() calls? Like i want to do something with the returned value and then based on that do another evaluate on the page.Boccie

© 2022 - 2024 — McMap. All rights reserved.