我正在创建一个扩展,我必须在用户在 Google Plus 中键入消息(状态)的 contenteditable div 上模拟空格键按键。
如果您打开 plus.google.com 并单击必须输入消息的 div,您会意识到,当您在消息中输入链接并按 {spacebar} 时,您会注意到 Google 会检索标题、图像和描述那个链接。我试图模拟空格键按键 3 天。我已经可以在表单元素上模拟鼠标悬停,我可以在发送按钮中模拟 click(),但我仍然无法模拟空格键按键。
到目前为止,我最好的代码是:
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : " ", char : " ", shiftKey : false, keyCode: 32, which: 32, view: window});
//I need to delete the e.keyCode and e.which cause Chrome sets it as a readonly but for some reason if you delete it and assign a new value Chrome accepts (I am very sure this is a serious bug that I discovered in Chrome and that I already reported yesterday in theis bug tracker)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 32});
delete e.which;
Object.defineProperty(e, "which", {"value" : 32});
$(".Cla").find(".be.c-B").children().eq(1).get(0).dispatchEvent(e);
太感谢了。
编辑:
我不知道它是否可以帮助您进行测试,但我建议您这样做:
opened_window = window.open("http://plus.google.com");
之后单击 div 将其展开,然后运行以下代码:
$(".Cla").find(".be.c-B").children().eq(1).html("The site stackoverflow.com is amazing");
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : " ", char : " ", shiftKey : false, keyCode: 32, which: 32, view: window});
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 32});
delete e.which;
Object.defineProperty(e, "which", {"value" : 32});
$(".Cla").find(".be.c-B").children().eq(1).get(0).dispatchEvent(e);
由于某种原因,这不会触发链接信息的检索。但是,如果您只是单击 div 并按空格键,您将看到 Google 检索有关该链接的信息。