Search code examples
javascriptphantomjscasperjsevaluate

Declaring a variable with casper.evaluate


In the following example I'm trying to declare a global variable named foo in the using evaluate. And then outputing it using using the script on the webpage. But an error message indicates the variable has not been defined.

The webpage : index.html

<html>
<head>
  <meta charser="utf-8">
  <title> Page title </title>
</head>
<body>
  <script>
  window.onload = function() {
    console.log('started webpage script');
    console.log(foo);
  };
  </script>
</body>
</html>

Casper script : casper.js

var casper = require('casper').create({
  verbose : true,
  logLevel : "debug"
});


casper.start('http://localhost:8080');

casper.on('page.error', function(err) {
  this.echo(err, 'ERROR');
});


casper.on('remote.message', function(msg) {
  this.echo(msg);
});

casper.on('run.start', function() {
  casper.evaluate(function() {
    console.log('Running evaluate script');
    window.foo = "Hello world!";
  });
});


casper.run();

Terminal output

[info] [phantom] Starting...
[info] [phantom] Running suite: 2 steps
[debug] [phantom] Successfully injected Casper client-side utilities
Running evaluate script
[debug] [phantom] opening url: http://localhost:8080/, HTTP GET
[debug] [phantom] Navigation requested: url=http://localhost:8080/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://localhost:8080/"
started webpage script
ReferenceError: Can't find variable: foo
[debug] [phantom] Successfully injected Casper client-side utilities
[debug] [phantom] start page is loaded
[info] [phantom] Done 2 steps in 65ms

Solution

  • I needed to call casper.evaluate() on page.initialize

    casper.on('page.initialize', function() {
      casper.evaluate(function() {
        console.log('Running evaluate script');
        window.foo = "Hello world!";
      });
    });