javascript - 如何监听页面加载时触发的事件

标签 javascript testing phantomjs casperjs

如何编写可以监听页面加载时触发的事件的 CasperJS 测试?我感兴趣的事件在页面正文末尾触发。

// my-page.html
<html>
  ...
  <body>
    ...
    <script type="text/javascript">
      $(function() {
        fireInterestingEvent();
      });
    </script>
  </body>
</html>

我试过注入(inject)客户端脚本,但它似乎在 fireInterestingEvent() 已经触发后加载。

// test/my-test.js
casper.options.clientScripts.push("test/lib/my-client-script.js")

// test/lib/my-client-script.js
listenToInterestingEvent();

我也试过在页面加载完成之前初始化一个测试对象,但我的对象没有留在 DOM 上。

// test/my-test.js
casper.on('load.started', function() {
  this.evaluate(function() {
    window.testObject = { foo: 'bar' };
  });
});

// my-page.html
<script type="text/javascript">
  if (window.testObject) listenToInterestingEvent(); // window.testObject is undefined
  fireInterestingEvent();
</script>

最佳答案

@Artjom B. 在评论部分弄明白了。在 url.changed 期间初始化 window 上的对象有效,但在 load.started 期间无效。

// test/my-test.js
casper.on('url.changed', function() {
  this.evaluate(function() {
    window.testObject = { foo: 'bar' };
  });
});

// my-page.html
<script type="text/javascript">
  if (window.testObject) listenToInterestingEvent();
  fireInterestingEvent();
</script>

关于javascript - 如何监听页面加载时触发的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002271/

相关文章:

javascript - c# 字符串数组转 JS 数组

javascript - pjax 成功后仅通过单击特定输入显示消息

安卓测试 : use Dagger2 + Gradle

javascript - 为什么在 Chrome 中有效的正则表达式在 Poltergeist/PhantomJS 中不起作用?

javascript - 如何从 PHP 执行 PhantomJS

javascript - 从 array.find() 中返回变量

测试微服务?

node.js - 未找到 Mocha 测试 : "0 passing"

centos - Phantomjs 文本符号不显示为 html 到 pdf

javascript - 无法让函数正确执行