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>
Related
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>
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);
Solved, see answer below
I test a React app with selenium.
I need to change the value of an input field, which is linked to the state of the object. In short (relevant parts of the code), a change in this input allows it's value to be submited only if it is not empty:
# react object
render: function(){
<input ... onChange={this.handleTextChange} className="myInput" />
<button onClick={this.handleSubmit}>Submit</button>
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function() {
if(this.state.text.length > 0) {
// relevant code that is never executed
// because although we change the value of the input, the state does not update
}
},
The code works but I cannot find a way to test it because I cannot find any js manipulation which would update the input AND reflect in the state of the object.
I tried the following solutions
# value update
self.selenium.execute_script("var input = document.querySelectorAll('input.myInput')[0]; form.value = 'New message!'");
The word 'New message!' actually appears in the input but does not update the state of the object.
I then tried focusing on the input and triggering a keyup event, without success
# try focus and keyUp
# source https://stackoverflow.com/questions/596481/simulate-javascript-key-events
self.selenium.execute_script("""
var form = document.querySelectorAll("input.messageFormInput")[0];
form.focus();
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
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.dispatchEvent(keyboardEvent);
""")
I tried the same solution with jQuery as explained here (Is it possible to simulate key press events programmatically?), but it does not work either.
Any idea is very welcome. Thanks!
My bad, I was not aware of
self.selenium.find_elements_by_class_name('myClass')[0].send_keys("hello")
Which actually solves the issue. Thanks to Chris Hawkes for sending me in the right direction.
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.
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.