I'm developing a Google Chrome extension which simulates keyboard events on a web-page.
I found that event.initKeyboardEvent()
does not work properly because of this webkit bug and I also found some workarounds, e.g. SO Question
However, defining properties on event object is not working because extension's content script has its own "parallel world" so properties defined in content script are not visible to web-page script.
My only and last hope that DOM 4 Event Constructors work in Google Chrome and it would be possible to properly initialize keyboard event through constructor
var event = new KeyboardEvent("keypress", {key: 'U+0041', char: 'a', ... })
Unfortunately, it fails with:
TypeError: illegal constructor
I was not able to find any documentation on supported event constructors in Chrome. Could anyone point me to some docs/source code?
Any other way to simulate keyboard events in a Google Chrome extension?
(note, TextEvent won't help because many real-world controls listen to keydown
/keyup
specifically)
Incase anyone has the issue I faced with triggering a keyup with a specific keycode. This is one way.
First off I tried @RobW's answer above with no luck. No Keycode passed, always undefined.
So then I looked into @disya2's answer, which did work.
So here's some code:-
Manifest
"permissions": [
"debugger"
],
ContentScript.js
chrome.runtime.sendMessage({ pressEnter: true });
Background.js
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.pressEnter){
chrome.tabs.query({active: true}, function(tabs) {
chrome.debugger.attach({ tabId: tabs[0].id }, "1.0");
chrome.debugger.sendCommand({ tabId: tabs[0].id }, 'Input.dispatchKeyEvent', { type: 'keyUp', windowsVirtualKeyCode:13, nativeVirtualKeyCode : 13, macCharCode: 13 });
chrome.debugger.sendCommand({ tabId: tabs[0].id }, 'Input.dispatchKeyEvent', { type: 'keyDown', windowsVirtualKeyCode:13, nativeVirtualKeyCode : 13, macCharCode: 13 });
chrome.debugger.detach({ tabId: tabs[0].id });
});
}
});