PhantomJS sendEvent () 模拟点击、按键用法与示例


发布日期 : 2020-09-20 19:39:58 UTC

访问量: 9 次浏览

PhantomJS sendEvent()

sendEvent() 用于将事件发送到网页。它们不是DOM事件。这些事件根据用户交互发送到网页。

sendEvent() 方法支持的事件是鼠标和键盘事件。

鼠标事件

SendEvent (mouseEventType [, mouseX, mouseY, button = 'left'])

MouseEventType- 这是一种事件类型,支持 mouseup, mousedown, mousemove, doubleclickclick

MouseX**和**MouseY 事件是可选的,用于获取鼠标的位置。button 参数定义了要按下的按钮,默认为左侧按钮。对于 mousemove 事件,没有按下按钮,因此不考虑 button

键盘事件

SendEvent (keyboardEventType, keyOrKeys, [null, null, modifier])

KeyboardEventType− 这是一个事件类型,支持 keyup , keypresskeydown

Keyorkeys− 第二个参数是页面事件中的键或字符串。第三和第四个参数不被考虑,需要传递NULL。

Modifier− 这是一个整数,并具有以下列表:

  • 0− 没有按下修饰键。
  • 0x02000000− 键盘上按下了Shift键。
  • 0x04000000− 键盘上按下了Ctrl键。
  • 0x08000000− 键盘上按下了Alt键。
  • 0x10000000− 键盘上按下了Meta键。
  • 0x20000000− 按下了键盘上的数字键。

语法

sendEvent() 语法如下:

sendEvent(mouseEventType[, mouseX, mouseY, button = 'left'])

示例

让我们举一个示例来理解 sendEvent() 方法的用法。

var page = require('webpage').create();
page.onAlert = function(msg) {
console.log(msg);
}
page.open('http://localhost/tasks/click.html', function(status) {
var element = page.evaluate(function() {
return document.querySelector('.mybutton');
});
page.sendEvent('click', element.offsetLeft, element.offsetTop, 'left');
console.log('element is ' + element);
});

click.html

<html>
<body>
<form>
<input type = "button" class = "mybutton" value = "Click me" onclick = "clickme()">
</form>
<p>welcome to phantomjs</p>

<script>
function clickme() {
alert("Hello world!");
}
</script>
</body>

</html>

上述程序生成以下输出

Hello world!
element is [object Object]