1

I'm trying to navigate through pages of an online dictionary. Here is my code:

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

var links = [];
function goToLink(linkName){
    nightmare
        .goto(linkName)
        .evaluate( () => {
            var href = document.querySelector("span.next a").href;
            links.push(href)
            return href;
        })
        .then((href) => {
            goToLink(href);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
}

goToLink("http://lexicon.quranic-research.net/data/01_a/000_!.html");

I'm getting Error: links is not defined. Links is clearly defined at var links = []; but the inner function doesn't know about it. What is going on here?

3
  • 3
    I could imagine that evaluate stringifies the argument and evals it ina different context. Edit: see github.com/segmentio/nightmare/issues/89 Commented Mar 12, 2017 at 16:41
  • You got it Felix. How do I accept a comment as the answer? Commented Mar 12, 2017 at 16:43
  • @FelixKling please add the comment as a response. Commented Mar 12, 2017 at 17:08

1 Answer 1

1

The problem is that evaluate callback is called in a different context and doesn't see links. What you can try to do is to pass it like this:

(...)
.evaluate( links => {
    var href = document.querySelector("span.next a").href;
    links.push(href)
    return href;
}, links)
(...)

links are the parameter of the callback. You have to pass it as a second parameter in the evaluate function.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah you can pass an argument. Cool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.