【问题标题】:Declaring a variable with casper.evaluate用 casper.evaluate 声明一个变量
【发布时间】:2014-05-23 01:40:09
【问题描述】:

在下面的示例中,我试图在 using 评估中声明一个名为 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

【问题讨论】:

  • 是否尝试过将 run.start 更改为正在启动或已启动?在 run.start 中根本没有网页可以注入您的 js。您可能还想查看事件 page.created 和 page.initialized
  • 你有没有试过先在网页上声明变量,然后从casper赋值?
  • page.initialized 做到了,谢谢
  • @YoussefBouhjira 您可以分享您的解决方案作为答案。

标签: javascript phantomjs casperjs evaluate


【解决方案1】:

我需要在 page.initialize 上调用 casper.evaluate()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多