0

I am working on casperjs. I write following program to get output:

var casper = require('casper').create();
var cookie;
casper.start('http://wordpress.org/');
casper.then(function() {
       this.evaluate(function() {
            cookie=document.cookie;
       })
   })

casper.then(function() {
console.log("Page cookie");
console.log(cookie);
})
casper.run(function() {
 this.echo('Done.').exit();
})

Output for above is:
Page cookie
undefined
Done.

why it give me undefined? Help me into this.

Suraj Dalvi
  • 988
  • 1
  • 20
  • 34
  • possible duplicate of [CasperJS passing variable to evaluate can't get it to work](http://stackoverflow.com/questions/22597987/casperjs-passing-variable-to-evaluate-cant-get-it-to-work) – Artjom B. Jul 20 '15 at 10:06
  • Here is another duplicate: [How do I set a variable from casper.evaluate()?](http://stackoverflow.com/questions/30091901/how-do-i-set-a-variable-from-casper-evaluate) – Artjom B. Jul 20 '15 at 10:07

2 Answers2

1

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.

-2

remove var cookie

        cookie = casper.evaluate(function() {
                 return document.cookie;
         })
        casper.then(function() { 
                console.log("Page cookie");    
                console.log(cookie);        
        })

The above code works fine for me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129