Programatically trigger keydown event with `which` property - javascript

How can I programatically trigger keydown event on Chrome that is going to have which property set to desired value?
tried
new KeyboardEvent('keydown', {
'which':65,
'charCode':65,
'keyCode':65,
'key':"a",
'code':"KeyA",
});
but when receiving the property in input's onKeyDown handler, the event has which,charCode and keyCode equal to 0. key is correctly set to a.

In Chrome, those event properties have default values of 0 and are not writable (due to their being deprecated). You have to delete the native properties and then re-create them:
var ke = new KeyboardEvent('keydown', {
'key':"a",
'code':"KeyA",
});
// Delete native event read-only properties with default values of 0
delete ke.keyCode;
delete ke.charCode;
delete ke.which;
// Create new custom properties that are read/write:
Object.defineProperty(ke, "keyCode", {"value" : 65});
Object.defineProperty(ke, "charCode", {"value" : 65});
Object.defineProperty(ke, "which", {"value" : 65});
var el = document.getElementById("key");
el.addEventListener("keydown", function(evt){
console.log(evt.key, evt.code, evt.keyCode, evt.charCode, evt.which);
});
el.dispatchEvent(ke);
<input type="text" id="key">

Related

simulated call onMouseDown in console

There is a div element on the page, by clicking on it a menu with a choice of the displayed number of elements is created.
Menu:
How to call this action through the console (onMouseDown React)?
Code:
In the console you want to grab your element and then use a dispatch event to simulate a mouseover or click
var div = document.querySelector("#myDiv");
var myEventToDispatch = new MouseEvent("click"); //or "mousedown", whichever you need
div.dispatchEvent(myEventToDispatch);
These three lines in your console should do the trick.
Checkout: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent for more options
found a solution, works in practice. The menu implementation on the site consisted of several nested divs and one input. None of these elements responded to the click () function. The solution below solved my problem and the next steps I needed.
<pre><code>
var MENU = IFrame.contentDocument.getElementsByClassName("class box menu")[0]; // getElementsById, getElementsByTag[0] ....
MENU = MENU.getElementsByTagName("div");
var MaxList = MENU[1].getElementsByTagName("input")[0];
if(MaxList != undefined)
{
if(MENU[0].textContent != "100 items")
{
// focus menu
MaxList.focus();
var e = new KeyboardEvent(
"keydown",
{
bubbles : true,
cancelable : true,
key : "ArrowDown",
char : "ArrowDown",
shiftKey : true
}
);
// scroll down the list
MaxList.dispatchEvent(e);
MaxList.dispatchEvent(e);
MaxList.dispatchEvent(e);
// choice
e = new KeyboardEvent(
"keydown",
{
bubbles : true,
cancelable : true,
key : "Enter",
char : "Enter",
shiftKey : true
}
);
MaxList.dispatchEvent(e);
}
}
</code></pre>
VKomyak (Volt_Nerd)

cannot find non-jQuery equivalent for "trigger"

Tigran Saluev suggested the following answer to manually triggering a prompt to select a file, but the code used jQuery. His code was a follows:
var input = $(document.createElement("input"));
input.attr("type", "file");
input.trigger("click");
In my project, I wanted the equivalent effect but without jQuery. I thought I had it here:
var input = document.createElement("input");
input.setAttribute("type", "file");
input.dispatchEvent(new Event("click"));
But nothing happens. What am I doing incorrectly?
In your case a simple click() call is all that is needed to trigger the event. Or if you want to use dispatch event, you want to create a Mouse Event and trigger that.
var fi = document.querySelector("#f");
// simple call to click()
document.querySelector("button.test1").addEventListener("click", function() {
f.click()
});
// Or with dispatch event
document.querySelector("button.test2").addEventListener("click", function() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
fi.dispatchEvent(event);
});
<input id="f" type="file" />
<button class="test1" type="button"> CLICK ME 1</button>
<button class="test2" type="button"> CLICK ME 2</button>
you can use initMouseEvent as an alternative to trigger
here's link to it to the api, for more details
function clickSimulation(id) {
var theEvent;
var theElement = document.getElementById(id);
if (document.createEvent) {
theEvent = document.createEvent("MouseEvents");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
(theEvent) ? theElement.dispatchEvent(theEvent) : (theElement.click && theElement.click());
}
var input = $(document.createElement("input"));
input.attr("type", "file");
input.attr("id", "TheFileCatcher");
clickSimulation("TheFileCatcher");
I think you were just missing an event listener. Try the following construction:
// Create an input object
var input = $(document.createElement("input"));
input.attr("type", "file");
// Add an event listener
input.addEventListener("click", function(e) {
console.log(e.detail);
});
// Create the event
var event = new CustomEvent("click", { "detail": "My click event" });
// Dispatch/Trigger/Fire the event
input.dispatchEvent(event);
You can also try "playing" with an event types, so instead of CustomEvent you can try the same you did in your code, because click is not a custom one. I assume that the problem is because you are missing an event listener
Ref to the original answer
EDIT Found an info about security restriction for triggering file input programmatically
Most browsers prevent submitting files when the input field didn't receive a direct click (or keyboard) event as a security precaution. Some browsers (e.g. Google Chrome) simply prevent the click event, while e.g. Internet Explorer doesn't submit any files that have been selected by a programmatically triggered file input field. Firefox 4 (and later) is so far the only browser with full support for invoking "click"-Events on a completely hidden (display: none) file input field.

How to detect Click + [Shift, Ctrl, Alt] in reactjs click event?

I want to do some other things when user Click+[Ctrl], but it seems that I could not detect if user press Ctrl when clicking.
I copy the event object infos below.
bubbles : false
cancelBubble : false
cancelable : false
currentTarget : react
defaultPrevented : false
eventPhase : 2
isTrusted : false
path : Array[1]
returnValue : true
srcElement : react
target : react
timeStamp : 5690056.695
type : "react-click"
I can see the ctrlKey attribute in the arguments[0]-Proxy Object. But this object is unaccessable('Uncaught illegal access'):
[[Target]]
:
SyntheticMouseEvent
_dispatchInstances:ReactDOMComponent
_dispatchListeners:(e)
_targetInst:ReactDOMComponent
altKey:false
bubbles:true
button:0
buttons:0
cancelable:true
clientX:275
clientY:315
ctrlKey:false
Your click handling function would have a format as such:
clickHandler: function (event, value) {
event.stopPropagation();
// In that case, event.ctrlKey does the trick.
if (event.ctrlKey) {
console.debug("Ctrl+click has just happened!");
}
}
you can use this code below in your render() method
document.addEventListener('click', (e) => {
if (e.ctrlKey) {
console.log('With ctrl, do something...');
}
});
In the click event of this element you can check if at the moment of the click, a button (with keycode of ctrl in this case) is pressed down

javascript dispatchEvent Keypress, returns true , but input field is still empty

I need to trigger or say dispatchEvent KeyPress inside an Input box,
I have tried a lot with "initKeyboardEvent" , "initKeyEvent" , "createEvent", even I found similar question's answers but nothing seems to work, neither in firefox, nor in chrome (I think they may be deprecated), as
KeyboardEvent.initKeyEvent(), is deprecated.
like we have
document.getElemntByID('button').click();
I want to do something like:
document.getElemntById('email').keyPress(charCode('a'));
but unfortunately I am not able to make keypress work in any way.
I know it is possible in jQuery , but I want to do it in pure javascript, after all jquery uses Javascript in backend , so there must be a way , if I am not wrong.
====Update=========
I wonder
window.addEventListener('keydown', keyDown(), true);
function keyDown(){
alert('keydown');
}
var fireOnThis = document.getElementById('pwph');
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keydown', true, true, window, false, false, false, false, 72, 0 );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keydown', true, true, window, 1 );
evObj.keyCode = 72;
}
fireOnThis.dispatchEvent(evObj);
This code returns me true , and even the eventListner is catching this event, then why am I not able to see any text inside the input box?
====================update============================
This seems to work for everyone, but why does it leaves my text field empty, even after returning true?
// Create the event
var evt = document.createEvent( 'KeyboardEvent' );
// Init the options
evt.initKeyEvent(
"keypress", // the kind of event
true, // boolean "can it bubble?"
true, // boolean "can it be cancelled?"
null, // specifies the view context (usually window or null)
false, // boolean "Ctrl key?"
false, // boolean "Alt key?"
false, // Boolean "Shift key?"
false, // Boolean "Meta key?"
9, // the keyCode
0); // the charCode
// Dispatch the event on the element
el.dispatchEvent( evt );
I was trying to dispatch a keyPress event inside an Input element to pass the data-bind condition(KnockOut js) event , but unfortunately KeyPress didn't worked for me, Instead I used change event in place of it.
so I did this:
element = document.getElementById('idTxtBx_SAOTCS_ProofConfirmation');
element.value = '8885'; // this alone was not working as keypress.
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true); // adding this created a magic and passes it as if keypressed
element.dispatchEvent(evt);
so .value and change event together made, fake inputText or keypressed event successful.
i think so like you want to add event listener on input box
var element = document.getElementById("email");
document.getElementById("email").addEventListener("keypress", function() {
console.log("keypresh")
})
var evt = document.createEvent("KeyboardEvent");
evt.initEvent("keypress", false, true);
// adding this created a magic and passes it as if keypressed
element.dispatchEvent(evt);

simulate ctrl + click with javascript or jquery (to open a new tab without focus)

I am playing with the jquery event object but I am stuck as hell
I read the API https://api.jquery.com/category/events/event-object/ but it's not really helping here, I am not even sure it's a good lead to do that
Do you have any suggestion ( the problem is to do the exact ctrl + click on a link). I saw some posts about it but nothing seems to work on the recent browsers
very simple exemple :
<span id="toto">toto</span>
// The goal is when I click on #toto, I would like #inANewTab trigger
// in a new tab without focus. To do that I was thinking
// about replicate a ctrl+click event
$('#toto').click(function(){
???
})
Edit:
The Event object in jQuery has a parameter for ctrlKey, you could assign that as true, on click.
var e = jQuery.Event("click");
e.ctrlKey = true;
$('#id').trigger(e);
Reference: jquery trigger ctrl + click
In pure javascript, you can use the MouseEvent for that:
document.getElementById("todo").dispatchEvent(new MouseEvent("click", {ctrlKey: true}));
To programatically open a new tab you can do that:
const a = document.createElement("a");
a.setAttribute("href", "https://www.google.com/");
a.dispatchEvent(new MouseEvent("click", {ctrlKey: true}));
This is a non-jQuery version to simulate keyboard events. This works in both Chrome (WebKit based) and Firefox (Gecko based):
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);
Or using jQuery, you can simulate by jQuery's event object:
jQuery.event.trigger({
type: 'keypress',
which: character.charCodeAt(0)
});

Categories

Resources