segment-boneyard / nightmare

A high-level browser automation library.
https://open.segment.com
19.54k stars 1.08k forks source link

Save Evaluated Result To A Variable #1610

Closed xcage7 closed 4 years ago

xcage7 commented 4 years ago

Here is a snippet of the code...

    .goto('https://google.com/')
    .type('#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input', 'github')

    .evaluate(() => document.querySelector('#rso > div:nth-child(1) > div > div > div.r > a > h3').href)
    .then(console.log)

    .catch((err) => {
        console.log(err)
    })

    const aa = nightmare.evaluate(() => document.querySelector('#rso > div:nth-child(1) > div > div > div.r > a > h3').href)

What i wanted to do is, save the outcome of the .evaluate to a global variable to use it later... How can I correct this code>

aleks5d commented 4 years ago

You can use .then() construction

const Nightmare = require('nightmare'); 
let nightmare = Nightmare({show: true});
let Enter = '\u000d';

async function main() {

    let aa;

    await nightmare
        .goto('https://google.com/')
        .type('#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input', 'github' + Enter)
        .evaluate(() => document.querySelector('#rso > div:nth-child(1) > div > div > div.r > a').href)
        .end()
        .then(text => {aa = text});

    console.log(aa);
}

main();