Concept behind evaluate is, you will pass your code to browser's console and execute your code there. If you define any variable inside evaluate method that variable will be local to that method. That scope is local. When you are dealing with Casper you should consider the scope of the variable.
So when you try to print out "cookie" in the main function it will say it is undefined.Which is expected.
note that you cant use echo (),console.log () inside evaluate method.
cookie = this.evaluate(function() {
var cookieLocal=document.cookie;
return cookieLocal;
})
Here "cookieLocal" is a local variable.
This will return value to Gloabal variable "cookie". So when you try to print the value in the main function it will work as expected. I hope this will make you to consider scope when declaring variable. You can directly return do the return . No Need of using local variable.
cookie = this.evaluate(function() {
return document.cookie;
})
Another important thing i recommend when you using an evaluate method. try to use Try catch method while developing the code. It wont be needed in production as per you requirement. We cannot print anything inside console. so use try catch for debugging purpose.
casper.then(function() {
cookie = this.evaluate(function() {
try {
return document.cookie;
} catch (e) {
return e;
}
})
this.echo (JSON.stringify ('cookie :'+cookie));
})
Note that this.echo () should be outside evaluate method.
Hope this will be an helpful one.