因为当您从内容脚本向页面发起事件(反之亦然)时,Chrome 不会保留自定义属性,所以在页面中注入一个脚本来接管这项工作。这是一个显示这个想法的基本示例。它是可用的,尽管key
和keyCode
属性没有正确处理(无论如何都不应该使用)。
// Example: Say, you've got a reference to a DOM element...
var elem = document.body;
// And you want to "type" "A"
var charCode = 65;
// Now, you want to generate a key event...
triggerKeyEvent(elem, charCode);
// triggerKeyEvent is implemented as follows:
function triggerKeyEvent(element, charCode) {
// We cannot pass object references, so generate an unique selector
var attribute = 'robw_' + Date.now();
element.setAttribute(attribute, '');
var selector = element.tagName + '[' + attribute + ']';
var s = document.createElement('script');
s.textContent = '(' + function(charCode, attribute, selector) {
// Get reference to element...
var element = document.querySelector(selector);
element.removeAttribute(attribute);
// Create KeyboardEvent instance
var event = document.createEvent('KeyboardEvents');
event.initKeyboardEvent(
/* type */ 'keypress',
/* bubbles */ true,
/* cancelable */ false,
/* view */ window,
/* keyIdentifier*/ '',
/* keyLocation */ 0,
/* ctrlKey */ false,
/* altKey */ false,
/* shiftKey */ false,
/* metaKey */ false,
/* altGraphKey */ false
);
// 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
});
element.dispatchEvent(event);
} + ')(' + charCode + ', "' + attribute + '", "' + selector + '")';
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
// The script should have removed the attribute already.
// Remove the attribute in case the script fails to run.
s.removeAttribute(attribute);
}
这是一个触发keypress
字符“A”事件的简单示例。如果要触发更多相关的关键事件,不要使用triggerKeyEvent
3次(因为它有轻微的开销)。相反,修改triggerKeyEvent
函数,使其使用正确的参数触发所有事件( keydown
、keypress
和keyup
/或)。input
如果您需要能够更改altKey
,shiftKey
等,只需修改功能即可。
底线:我展示的示例非常基本,可以根据您的需要进行调整。
阅读更多
如果您想更改实现以匹配规范,请阅读以下来源:
如果您想了解更多关于内容脚本中脚本注入的概念,请参阅: