我正在开发一个chrome扩展程序,该扩展程序模拟按键提交表单。只要我停留在页面上并且不切换选项卡,此方法就很好用。当我切换选项卡时,表单不会填写相同的内容。
奇怪的是,replaceCommentHtmlAndSetSender
函数似乎在提交一个评论并触发keypress事件后无法正确传播信息。如果我单击返回页面,则该扩展程序有效。
我尝试使用monitorEvents(window)
在控制台中查看所有事件,它们似乎是相同的。我也尝试过在window.focus()
中添加一个replaceCommentHtmlAndSetSender
事件,但不走运。
哪些事件/差异可能会导致选项卡离开导致这种行为?
var replaceCommentHtmlAndSetSender = function(reply_link, resp, id) {
$(document.activeElement).sendkeys("txt")
setTimeout(function() {
var str = '<span data-text="true" data-comment-sender="true">txt >/span>'
$(document.activeElement).replaceWith(str)
})
submitComment()
}
var submitComment = function() {
var foundElementScript = document.createElement("script")
foundElementScript.textContent = "foundElement()"
document.head.appendChild(foundElementScript)
foundElementScript.parentNode.removeChild(foundElementScript)
}
// this script is injected into the page
function foundElement(){
found=document.querySelectorAll('[data-comment-sender="true"]')[0];
found.setAttribute("data-comment-sender", "false");
submitComment(found);
}
}
function submitComment(element) {
var event;
if(document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent('keydown', true, true);
} else {
event = document.createEventObject();
event.eventType = 'keydown';
}
event.eventName = 'keydown';
event.keyCode = 13;
event.which = 13;
if(document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent("on" + event.eventType, event);
}
}