出于安全原因,CasperJS 仅调用不会触发 Flash 鼠标事件的 javascript 事件。
然而,PhantomJSsendEvent
方法调用真实的浏览器事件。
下一个问题是元素必须在当前视口中可见,这在大多数情况下需要 scolling。
最后我写了一个小的 CasperJSclickRelative
扩展:
casper.clickRelative = function (selector, offset) {
"use strict";
var docSize = casper.evaluate(function () {
return {width: document.width, height: document.height};
});
var position = this.getElementBounds(selector);
if (position !== null) {
var left = position.left + (offset.left || 0);
var scrollX = this.page.viewportSize.width > docSize.width ? 0 :
Math.min(left, docSize.width - this.page.viewportSize.width);
var top = position.top + (offset.top || 0);
var scrollY = this.page.viewportSize.height > docSize.height ? 0 :
Math.min(top, docSize.height - this.page.viewportSize.height);
var scrollOrig = {left: this.page.scrollPosition.left, top: this.page.scrollPosition.top};
this.page.scrollPosition = {left: scrollX, top: scrollY};
this.wait(10);
this.then(function () {
this.page.sendEvent("click", left - scrollX, top - scrollY, 'left');
});
this.wait(10);
this.then(function () {
this.page.scrollPosition = scrollOrig;
});
}
};
所以现在我的脚本能够单击按钮并生成以下 Flash 按钮的屏幕截图:
var casper = require('casper').create({
pageSettings: {
loadPlugins: true
}
});
casper.start("http://www.adobe.com/devnet/flash/quickstart/button_component_as3.edu.html");
casper.wait(1000);
casper.then(function () {
this.echo("Click", "INFO");
// The button has a margin so we have to add a little offset to the
// click position:
this.clickRelative('#section04example1', {left: 30, top: 15});
});
casper.wait(1000);
casper.then(function () {
this.echo("Screenshot", "INFO");
this.captureSelector('button-demo.png', '#section04example1');
this.exit();
});
casper.run();