如何使用 casperjs 模拟键盘操作/事件?我在按下 shift + alt + Enter
、ctrl + }
和 ctrl + shift + >
等键盘操作时卡住了。 。
有人可以帮我做这些事情吗
尝试了以下内容
this.sendKeys('div.edit-code > textarea:nth-child(1)', 'enter', {modifiers: 'shift + alt'});
编辑:
我需要使用 this site 的键盘快捷键来执行单元格场景如下:
- 使用
'+'
符号创建一个新单元格 - 向单元格添加一些内容
- 现在使用键盘快捷键,需要执行(例如:
“shift+alt+enter”
单元格
最佳答案
我写了一个小测试用例:
keyboard.html(捕获键盘事件并将其写入div):
<script>
document.onkeypress = function (e) {
var keys = [e.ctrlKey ? "CTRL" : "", e.altKey ? "ALT" : "", e.shiftKey ? "SHIFT" : "", String.fromCharCode(e.keyCode)].filter(function (x) {
return x != "";
})
document.querySelector('#text').textContent = keys.join(" + ");
};
</script>
<div id="text">
</div>
Casper 脚本:
var casper = require('casper').create();
casper.start('http://localhost:63344/CasperSheet/keyboard.html');
function testKey(key, modifiers) {
casper.then(function () {
casper.sendKeys("#text", key, {modifiers: modifiers});
}).then(function () {
casper.echo(casper.evaluate(function () {
return document.querySelector("#text").textContent
}))
})
}
testKey('a');
testKey('}', 'ctrl')
testKey('>', 'ctrl+alt')
testKey('\n', 'shift+alt')
casper.run();
输出:
a
CTRL + }
CTRL + ALT + >
ALT + SHIFT +
//a new line here...
<小时/>
来看看你的代码,我的建议:
-
'enter'
应该是'\n'
。如果您使用'enter'
,它将发送'e'
,'n'
,'t'
,'e'
,'r'
五个关键的董事会事件... -
{modifiers: 'shift + alt'}
应该是{modifiers: 'shift+alt'}
。因为修饰符组合的实现不会 trim 空间...您可以向 CasperJS 发布拉取请求来修复该问题...
好吧,让我们讨论如何在该网络应用程序中运行代码...我发现我们可以通过单击 play
来运行代码按钮,因此无需通过 alt + shift + enter
运行代码这很难实现......
该脚本对我有用:
var casper = require('casper').create({
verbose: true,
logLevel: 'debug',
viewportSize: {
width: 1600,
height: 900
}
});
var cookie = "user=Sayalic0; token=<some_token>";
var domain = "rcloud.social";
cookie.split(";").forEach(function(pair){
pair = pair.split("=");
phantom.addCookie({
'name': pair[0],
'value': pair[1],
'domain': domain
});
});
casper.start('https://rcloud.social/edit.html?notebook=<note_book_id>')
casper.then(function () {
casper.wait(30000);//wait for page load
}).then(function () {
casper.capture('1.png')
}).then(function () {
casper.click("#run-notebook > i")// click run
}).then(function () {
casper.wait(10000)//wait code running ends
}).then(function () {
casper.capture('2.png');
})
casper.run()
屏幕截图:
关于javascript - 使用 casperjs 模拟键盘操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38325833/