我一直在努力解决谷歌扩展的问题,而你一直是我最后的希望! :))
好吧,我想点击Chrome扩展程序上的按钮,这会导致页面扩展程序上的keydown模拟正在运行。
我认为chrome在我的想法上有一些安全问题,它会阻止键盘模拟(使事件isTrusted:false)并删除哪个属性。
我写的函数在jsfiddle上运行正常,但看起来chrome扩展以不同的方式执行。
以下是内容脚本文件:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if(request.action == "scrollToTop"){
}
else if(request.action == "scrollToBottom"){
}
else if(request.action == "enter"){
triggerKeyboardEvent(document,13);
}
function triggerKeyboardEvent(el, keyCode){
var event = new Event("keydown", {"bubbles":true, "cancelable":true});
event.which = keyCode;
el.dispatchEvent(event);
}
});
chrome.runtime.sendMessage({action : "show"});
登录jsFiddle写道:
Event {isTrusted: false, which: 13}
登录网站:
document.addEventListener('keydown',function (e) {
console.log(e)
}
写道:
Event {isTrusted: false}
答案 0 :(得分:1)
感谢@ BG101和@Rob W我发现该解决方案是脚本注入!
唯一的事情就是根据MDN对KeyboardEvent.initKeyboardEvent()进行了描述,所以我用以下代码替换了代码:
var event = new Event(event, {"bubbles":true, "cancelable":true});
另外,由于我希望触发器在文档上运行,我删除了元素选择器。这是我得到的:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if(request.action == "scrollToTop"){
triggerKeyboardEventOnDocument("keydown",38);
}
else if(request.action == "scrollToBottom"){
triggerKeyboardEventOnDocument("keydown",40);
}
else if(request.action == "enter"){
triggerKeyboardEventOnDocument("keydown",13);
}
function triggerKeyboardEventOnDocument(event, keyCode){
var script = document.createElement('script');
script.textContent = '(' + function(event, charCode) {
//Create Event
var event = new Event(event, {"bubbles":true, "cancelable":true});
// Define custom values
// This part requires the script to be run in the page's context
var getterCode = {get: function() {return charCode}};
var getterChar = {get: function() {return String.fromCharCode(charCode)}};
Object.defineProperties(event, {
charCode: getterCode,
which: getterCode,
keyCode: getterCode, // Not fully correct
key: getterChar, // Not fully correct
char: getterChar
});
document.dispatchEvent(event);
} + ')(' + '\"' + event + '\", '+ keyCode + ')';
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
}
});
chrome.runtime.sendMessage({action : "show"});