使用casper.evaluate声明变量

时间:2014-05-23 01:40:10

标签: javascript phantomjs casperjs evaluate

在下面的示例中,我试图在using evaluate中声明一个名为foo的全局变量。然后使用网页上的脚本输出它。但是错误消息表明该变量尚未定义。

网页: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脚本: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();

终端输出

[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

1 个答案:

答案 0 :(得分:0)

我需要在page.initialize

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