React emit KeyboardEvent from input - javascript

Is there a way to emit KeyboardEvent for input in React ?
I tried with:
this.input.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Backspace',
bubbles: true,
cancelable: false
}));
this.input.dispatchEvent(new KeyboardEvent('keyup', {
key: 'Backspace',
bubbles: true,
cancelable: false
}));
this.input.dispatchEvent(new KeyboardEvent('keypress', {
key: 'Backspace',
bubbles: true,
cancelable: false
}));
But none of this triggers any handler (onKeyDown, onKeyPress, onKeyUp).
Handlers are called on manually key press only ...

Related

Send input javascript, on Chrome

Does someone have any idea why only the second time I run my code it does work?
ThisElement = document.querySelector("#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text");
ThisElement.innerText = 'message';
var focusEvent = new FocusEvent('focus', {
bubbles: false,
cancelBubble: false,
cancelable: false,
composed: true,
currentTarget: null,
defaultPrevented: false,
detail: 0,
eventPhase: 0,
isTrusted: true,
});
ThisElement.dispatchEvent(focusEvent);
https://youtu.be/yrD9jB1FXHo
The code just sends a message in the search box.
I'm testing it on chrome using the DevTools console (F12).
The problem is with the React JS used to design whatsapp web, so to manage this you can call again event in the setTimeout
Reason behind this issue:
On the first event trigger the whatsapp web screen will release all the input focused from the app screen, so it is required to again trigger event to stimulate human action in browser.
function searchContact(contact_name = "") {
search = document.querySelector('#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text');
var focusEvent = new FocusEvent('focus', {
bubbles: true,
cancelBubble: false,
cancelable: true,
composed: true,
currentTarget: null,
defaultPrevented: false,
detail: 0,
eventPhase: 0,
isTrusted: true,
});
//Enter value in search box events
var inputEvent = new InputEvent('input', {
bubbles: true
});
search.textContent = contact_name;
search.dispatchEvent(focusEvent);
search.dispatchEvent(inputEvent);
setTimeout(function() {
search.textContent = contact_name;
search.dispatchEvent(focusEvent);
search.dispatchEvent(inputEvent);
el = document.querySelector("#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text");
var event = new KeyboardEvent('keydown', {
code: 'Enter',
key: 'Enter',
keyCode: 13,
view: window,
bubbles: true
});
el.dispatchEvent(event);
}, 1000)
}
searchContact("name");
function triggerMouseEvent(el, etype) {
console.log(el)
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent(etype, true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
el.dispatchEvent(evt);
}

How to fire Blur event to window with javascript

I set a text in a field with javascript, then I send change event to that field.
I would like to fire blur event on the window as the website require.
to set the text in the input field I use "document.getElementsByTagName('input')[23].value = 'London'"
to send change event to the input field I use
var o = document.getElementsByTagName('input')[23];
if (document.createEvent) {
var evt = document.createEvent('Events');
evt.initEvent('change', true, true);
o.dispatchEvent(evt); }
now I would like to send blur event but to window, I don t know how to do that.
this is the source code for the field :
<span class="next-input next-error next-large address-input">
<input height="100%" autocomplete="off" value="" data-spm-anchor-id="a2g0s.8850659.0.i9.2bdb6c37UwO8uq"></span>
this is the process that the website do :
change Event {isTrusted: true, type: "change", target: input, currentTarget: Window, eventPhase: 3, …}
blur
Event {isTrusted: true, type: "blur", target: Window, currentTarget: Window, eventPhase: 2, …}
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
defaultPrevented: false
eventPhase: 0
isTrusted: true
path: [Window]
returnValue: true
srcElement: Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
target: Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
timeStamp: 30631177.38000001
type: "blur"
__proto__: Event

Getting specific properties of custom object

I have a CustomEvent object that I need to retrieve specific properties for. This object is not a plain object, but rather is the result of new CustomEvent();. When I output this object in the [Chrome] browser console, I see the following:
CustomEvent{
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: Window {...}
defaultPrevented: false
detail: {...}
eventPhase: 0
isTrusted: false
path: [Window]
returnValue: true
srcElement: Window {...}
target: Window {...}
timeStamp: 4979.4150000670925
type: "resize_element"
}
When I use Object.keys(custom_event_obj), I get only one key, isTrusted. This would mean that isTrusted is the only enumerable key.
I use the following code to make sure:
for(var key_str in custom_event_obj)
{
console.log(key_str, 'property is enumerable =', custom_event_obj.propertyIsEnumerable(key_str))
}
And I get the following result:
isTrusted is enumerable = true
detail is enumerable = false
initCustomEvent is enumerable = false
NONE is enumerable = false
CAPTURING_PHASE is enumerable = false
AT_TARGET is enumerable = false
BUBBLING_PHASE is enumerable = false
type is enumerable = false
target is enumerable = false
currentTarget is enumerable = false
eventPhase is enumerable = false
bubbles is enumerable = false
cancelable is enumerable = false
defaultPrevented is enumerable = false
composed is enumerable = false
timeStamp is enumerable = false
srcElement is enumerable = false
returnValue is enumerable = false
cancelBubble is enumerable = false
path is enumerable = false
composedPath is enumerable = false
stopPropagation is enumerable = false
stopImmediatePropagation is enumerable = false
preventDefault is enumerable = false
initEvent is enumerable = false
Object.getOwnPropertyNames gives me only one key as well: isTrusted.
This list contains keys that don't appear in the browser console result.
I'd like to get just the keys that appear in the browser console. How do I filter those keys out from the full list above?
Object.getOwnPropertyNames gives me only one key as well: isTrusted.
Not for me:
let CustomEvent = {
bubbles: false,
cancelBubble: false,
cancelable: false,
composed: false,
currentTarget: null,
defaultPrevented: false,
detail: null,
eventPhase: 0,
isTrusted: false,
path: [],
returnValue: true,
srcElement: null,
target: null,
timeStamp: 4979.4150000670925,
type: "resize_element"
}
console.log(Object.getOwnPropertyNames(CustomEvent));
But, while that does get you the property names, you'll still have to loop over the object and get the values for the properties.
You can also use .hasOwnProperty to only enumerate the properties that are not inherited.
let CustomEvent = {
bubbles: false,
cancelBubble: false,
cancelable: false,
composed: false,
currentTarget: null,
defaultPrevented: false,
detail: null,
eventPhase: 0,
isTrusted: false,
path: [],
returnValue: true,
srcElement: null,
target: null,
timeStamp: 4979.4150000670925,
type: "resize_element"
}
for(var prop in CustomEvent){
if(CustomEvent.hasOwnProperty(prop)){
console.log(prop, CustomEvent[prop]);
}
}

How to get the textContent length of an event

I would like to retrieve the number of elements in an event.
I use the following function :
element.bind('keyup', function (event) {
console.log(event);
});
The console.log (event) resitute me an object like this one (object shortened for the rendering)
n.Event {originalEvent: KeyboardEvent, type: "keyup", isDefaultPrevented:
ƒ, timeStamp: 13561.044999980368, jQuery2140638708200199875: true, …}
altKey: false
bubbles: true
cancelable: true
char: undefined
charCode: 0
...
scrollTop: 0
scrollWidth: 1035
shadowRoot: null
slot: ""
spellcheck: true
style: CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "",
alignmentBaseline: "", all: "", …}
tabIndex: 0
tagName: "DIV"
textContent: "abc"
title: ""
translate: true
...
In this object I would like to retrieve in variable the value of the length of the textContent
textContent: "abc"
Here is a example :
https://codepen.io/gregand/pen/PoYevYQ?editors=1111
How can I recover this value ?
To achieve expected result, use below code
console.log(event.target.childNodes[0].length)
working code for reference - https://codepen.io/nagasai/pen/JjPvJoL?editors=1111

JSON.stringify losing properties - Logging and saving all javascript events

I am trying to log and save all the events that happens in a user session.
In order to do that, I'm having an array
var events = []
Having a listener for every event..
window.onload = function() {
window.addEventListener("abort", handleEvent);
window.addEventListener("blur", handleEvent);
[...]
}
and sending the events:
function sendEvents() {
axios.post('/api/logger', JSON.stringify(events));
}
The problem is that every sendEvents() is sending an array of events, but each of them have only two properties:
[{"isTrusted":true,"date":"2019-02-19T14:59:42.474Z"},{"isTrusted":true,"date":"2019-02-19T14:59:42.485Z"}
But it should have a LOT more properties, for example:
*altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 662
clientY: 273
composed: true
ctrlKey: false
currentTarget: null
date: Tue Feb 19 2019 12:08:38 GMT-0300 (hora estándar de Argentina) {}
defaultPrevented: false
detail: 0
eventPhase: 0
fromElement: null
isTrusted: true
layerX: 662
layerY: 273
metaKey: false
movementX: 0
movementY: 0
offsetX: 662
offsetY: 273
pageX: 662
pageY: 273
path: (7) [header.App-header, div.App, div#root, body, html, document, Window]
relatedTarget: null
returnValue: true
screenX: 662
screenY: 400
shiftKey: false
sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
srcElement: header.App-header
target: header.App-header
timeStamp: 1605.000000000473
toElement: header.App-header
type: "mouseover"
which: 1
x: 662
y: 273*
Even if I don't stringify the array, in the backend the object have only the same two attributes. (I'm using nodejs + mongodb)
How can I save the entire event object with all its properties?
There could be a couple reasons for this. Most likely is those properties are not enumerable which causes them to not be included in JSON. (Properties are defined as enumerable via Object.defineProperties.) See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description
I would recommend explicitly declaring which properties you want to POST, since you probably don't need all of them anyway:
axios.post('/api/logger', JSON.stringify(events.map(event=>{
return {
altKey: event.altKey,
bubbles: event.bubbles,
// etc...
}
}));

Categories

Resources