Is it possible to simulate shortcut key events programmatically on Chrome? - javascript

Is it possible to simulate shortcut key events programmatically on Chrome in JavaScript?
I just want to trigger the shortcut event in javascript and show the chrome extension popup.html without clicking the icon. I tried many ways,but failed.
Here is my javascript code:
<script>
function keypressEvt() {
var keyboardEvent = document.createEvent('KeyboardEvent');
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
keyboardEvent[initMethod](
'keypress', // event type: keydown, keyup, keypress
true, // bubbles
true, // cancelable
null, // view: should be window
true, // ctrlKey
false, // altKey
true, // shiftKey
false, // metaKey
0, // keyCode: unsigned long - the virtual key code, else 0
"P".charCodeAt(0), // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
}
document.addEventListener('keypress', function (e) {
console.log(event, 'ctrlKey: ' + e.ctrlKey, 'shiftKey: ' + e.shiftKey, e.char, e.key);
e.preventDefault();
});
// trigger
setTimeout(function () {
keypressEvt()
}, 2000)
</script>

Related

Trigger keypress event with event listener WITHOUT jquery

I want to trigger a keypress event as a reaction to an event listener without using jQuery
let arrow = document.querySelector("#arrow");
//When you click on the arrow
arrow.addEventListener('click', function(e){
// It triggers a keypress (down)
$(document).trigger(keypressing);
});
[EDIT] I tried this out, but doesn't seem to trigger the simulated keypress :
let arrow = document.querySelector(".scroll-down");
arrow.addEventListener('click', function(e){
console.log('simulating the keypress of down arrow')
document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'}));
});
$(window).bind('keypress', function(event) {
if (event.key == 'x') {
console.log('its working with x')
}
});
You can use dispatchEvent to trigger event.
Example: trigger keypress with key x
document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'}));
docs
This worked for me to trigger key down event:
// Create listener
document.addEventListener('keydown', () => { console.log('test')})
// Create event
const keyboardEvent = document.createEvent('KeyboardEvent');
const initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
keyboardEvent[initMethod](
'keydown', // event type: keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // view: should be window
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
40, // keyCode: unsigned long - the virtual key code, else 0
0 // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);
// Fire event
document.dispatchEvent(keyboardEvent);

Custom KeyboardEvent does not bubble

For some reason, my custom KeyboardEvent does not bubble.
I attend to handle holding key:
document.addEventListener('DOMContentLoaded', function () {
var isPressed = false;
var startTimeStamp;
document.addEventListener('keydown', function (e) {
if (!isPressed) {
startTimeStamp = e.timeStamp;
isPressed = true;
}
});
document.addEventListener('keyup', function (e) {
isPressed = false;
var eventDuration = e.timeStamp - startTimeStamp;
var _e = new KeyboardEvent('keyheld', {
bubbles: true,
cancelBubble: false,
cancelable: true,
char: e.char,
charCode: e.charCode,
key: e.key,
keyCode: e.keyCode,
which: e.which,
shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey,
altKey: e.altKey,
metaKey: e.metaKey
});
Object.defineProperty(_e, 'detail', {
value: {
duration: eventDuration
},
enumerable: true
});
document.dispatchEvent(_e);
});
});
And then I can handle keyheld event with a listener attached to document. Nonetheless, a listener attached to anything (below it is body) else does not fire at all:
document.addEventListener('DOMContentLoaded', function () {
document.body.addEventListener('keyheld', function (e) {
console.log('KEY HELD: ', e.detail.duration, e);
});
});
The code above does not work, what even stranger, even with true supplied as the third argument of addEventListener() which should fire a listener when capturing rather than bubbling.
What may be wrong here?
When you call document.dispatchEvent(event), the event is dispatched with its target set to document, which is the top-level node in the DOM hierarchy, as can be seen in an illustration here.
The event would normally bubble to the parents of the target element, but when the target is document, there are no parents (document.parentNode === null). Trying to register a capturing listener on the body doesn't work for the same reason.
You probably wanted to dispatch to the target of the original event: e.target.dispatchEvent(_e).

Programmatically pressing Alt 0 with JavaScript

What I'm trying to do is run a script (JS) that selects a test box. It's ID field name is JMan. Once it selects that field I am trying to programmatically have my code perform the key combination ALT+0 and then delay itself for 5 seconds. By the way I'm performing this in the IE browser.
function myFunction() {
var keyboardEvent = document.createEvent("keyboardEvent").;
document.getElementById("JMan");
}
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
true, // altKeyArgenter code here
false, // shiftKeyArg
false, // metaKeyArg
48, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
The detection event handler is a no-frills method of detecting Alt-0. You might consider more sophisticated checking to do things like determine if another key was pressed between the Alt and 0 (i.e this code will treat Alt-1-0 as if it were Alt-0 or Ctrl-Alt-0 as if it were Alt-0)(At least it checks if you hold down Alt-0). This is mainly because key events differ considerably between browsers and I wanted to make something that will hopefully work on the majority.
The button in this example fires a minimal "Alt-0" event designed for the event handler to catch (or you should be able to type Alt-0 into the window).
function fireAlt0() {
console.log("firing event");
window.dispatchEvent(new KeyboardEvent("keydown", { key: "0", altKey: true }));
}
function detectAlt0(event) {
if ("keydown" == event.type) { // we might want to use the same function for any of ( keydown, keypress, keyup ) events
if (event.key == "0" && event.altKey && !event.repeat) {
console.log("Open a window!");
}
}
}
window.addEventListener("DOMContentLoaded", function () {
// Use keydown because keypress won't fire for the Alt-0 combination (since it doesn't produce a visible character)
window.addEventListener("keydown", detectAlt0, false);
document.getElementById("button").addEventListener("click", fireAlt0, false);
}, false);
<button id="button">fireAlt0</button>

Simulate JavaScript Keypress on Text Field (Safari)

I`m trying to simulate a keypress event in a text field via javascript but seems that nothing works on Safari. I can see that some examples works at document level but none of them works with my text field.
Could please someone help-me? Thanks.
Here is my code:
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keypress", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
40, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.getElementById('mytextbox').dispatchEvent(keyboardEvent);
Obs: the textInput event don't work in my scenario.

Generating KeyboardEvent in vanilla Javascript - when event is caught, it has no key value in Chrome or Safari

Example here http://jsbin.com/yiyozepezi/edit?js,output
I am trying to generate some key events from within javascript, no jQuery. I want to trigger some events from my tests to make the code in the app react and do different things depending on the key.
A div is catching the event and printing some feedback
document.getElementById("theFeedback").addEventListener("keydown", (event) => {
console.log("KEYDOWN CAPTURED", event);
let str = "";
// have to manually enumerate fields as they are not enumerable
["code", "charCode", "keyCode", "key", "which", "altKey", "ctrlKey", "shiftKey"].forEach((k) => {
console.log("str", str);
str += `${k} = ${event[k]}<br>`;
});
document.getElementById("theFeedback").innerHTML = str;
});
And the button generates the event
document.getElementById("theButton").addEventListener("click", () => {
console.log("CLICK");
let keyEvent = new KeyboardEvent("keydown", { keyCode: 61, altKey: false, shiftKey: false, key: "q" });
document.getElementById("theFeedback").dispatchEvent(keyEvent);
});
EDIT Added code from a popular SO answer, but still no joy
document.getElementById("withKeyboardEvent").addEventListener("click", () => {
console.log("CLICK KeyboardEvent");
let keyEvent = document.createEvent("KeyboardEvent");
let initMethod = typeof keyEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyEvent[initMethod](
"keydown",
true, // bubbles oOooOOo0
true, // cancelable
window, // view
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
61,
0 // charCode
);
document.getElementById("theFeedback").dispatchEvent(keyEvent);
});
and
document.getElementById("withPlainEvent").addEventListener("click", () => {
console.log("CLICK withPlainEvent");
let keyEvent = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(keyEvent.initEvent){
keyEvent.initEvent("keydown", true, true);
}
keyEvent.keyCode = 61;
keyEvent.which = 61;
document.dispatchEvent ? document.dispatchEvent(eventObj) :
document.fireEvent("onkeydown", eventObj);
document.getElementById("theFeedback").dispatchEvent(keyEvent);
});
The event is triggered and captured ok. But in Chrome / Safari, the caught event has no keyCode / which / etc. I have tried all sort of combinations (I understand the topic is quite messy, and some properties are read only).
It all works fine as it is in Firefox.
shiftKey, altKey and ctrlKey are ok on all browsers.
It all works fine as it is if I use a physical keyboard - but not in the JSBin demo (I think they have their own craziness going on)
Any idea what may make it work?
Thanks.

Categories