Search code examples
javascriptphantomjscasperjs

casperjs does not recognize global variable stored between then statements


so I call the first url ... it returns a JSON object , I store the JSON object in a global variable called global_input .... and then I open a link using global_input.token

  var global_input = {'token' : 'xxx'} ;


    casper.start('http://localhost/client/charg/que' , function (content) {


     })
    .then(function() {
       global_input  = JSON.parse(this.getPageContent());
       casper.log( ' ==== token === > ' + global_input.token    , 'debug');

    })
    .thenOpen('http://localhost/client/charg/go/' + global_input.token , function() {

    })

    .run(function(){
        this.echo("DONE1");
        this.exit();
    });

here is the log

page init .....
[info] [phantom] Step anonymous 2/5 http://localhost/client/charg/que (HTTP 200)
[info] [phantom] Step anonymous 2/5: done in 725ms.
[info] [phantom] Step anonymous 3/5 http://localhost/client/charg/que (HTTP 200)
[debug] [phantom]  ==== token === > e608e91335fd622f430692d40e7ddf0f4b63428d
[info] [phantom] Step anonymous 3/5: done in 750ms.
[debug] [phantom] opening url: http://localhost/client/charg/go/xxx, HTTP GET

as you can see, even though the log shows the token being set to a new value

==== token === > e608e91335fd622f430692d40e7ddf0f4b63428d

in the next step i still get the default value of token which was xxx

[debug] [phantom] opening url: http://localhost/client/charg/go/xxx, HTTP GET

am I missing something ?


Solution

  • Your global_input is registered with it's initial value in the thenOpen method.

    like this

      casper.start(static url , callback method)
            .then(callback method)
            .thenOpen(static url (here, initial global object is used) , callback method)
            .run(callback method);
    

    So if you change anything in static_url, casperjs will not know as it already registered those urls in the casperjs' execution stack.

    You need to do like this

    var global_input = {'token' : 'xxx'} ;
    
    // this method will be called again when evaluating the url
    function getGlobalToken() {
        return global_input.token;
    }
    

    Now call get method like this

    thenOpen('http://localhost/client/charg/go/' + getGlobalToken() , function() {
    
        })