我正在创建一个扩展程序,我必须在contenteditable div上模拟一个空格键,用户在Google Plus中键入消息(状态)。
如果您打开plus.google.com并点击必须输入消息的div,您会发现当您在消息中键入链接并按{spacebar}时,您会发现Google会检索标题,图片和该链接的描述。我是3天试图模拟空格键keydown。我已经可以模拟鼠标悬停在表单的元素上,我可以在发送按钮中模拟click(),但我仍然无法模拟空格键keydown。
到目前为止,我最好的代码是:
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会检索有关该链接的信息。