Reputation: 28572
I want to use Nightmare
to access a page and do different operations based on whether a specified element exists. I know there is an exists
function to test whether an element exists on the page, but I don't know how to use it or whether it can be used here. Can someone give me an example on how to do this task? Thank you!
Upvotes: 1
Views: 2195
Reputation: 1686
Nightmare is thenable, so if you want to use the return value of an exists()
function as logic, you can use .then()
for method chaining. This also goes for visible()
or evaluate()
or any function returning a value.
The example I provided searches Stackoverflow if the searchbox selector exists, goes to Google, returns the title and then conditionally logs the result. You can continue chaining logic as necessary.
var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });
nightmare
.goto("http://stackoverflow.com")
.exists("#search input[type=text]")
.then(function (result) {
if (result) {
return nightmare.type("#search input[type=text]", "javascript\u000d")
} else {
console.log("Could not find selector")
}
})
.then(function() {
return nightmare
.goto("http://www.google.com")
.wait(1000)
.title()
})
.then(function (title) {
if (title == "Google") {
console.log("title is Google")
} else {
console.log("title is not Google")
}
return nightmare.end()
})
.catch(function (error) {
console.log(error)
})
Upvotes: 5