首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用casper.evaluate声明变量

用casper.evaluate声明变量
EN

Stack Overflow用户
提问于 2014-05-23 01:40:09
回答 1查看 570关注 0票数 0

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

网页: index.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
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();

终端输出

代码语言:javascript
复制
[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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-24 13:50:55

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

代码语言:javascript
复制
casper.on('page.initialize', function() {
  casper.evaluate(function() {
    console.log('Running evaluate script');
    window.foo = "Hello world!";
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23819747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档