JavaScript触发InputEvent.isTrusted = true [英] JavaScript trigger an InputEvent.isTrusted = true

查看:1295
本文介绍了JavaScript触发InputEvent.isTrusted = true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自动化 JavaScript 中的某些任务,并且需要使用 InputEvent ,但是当我使用常规事件时,我会我得到 event.isTrusted = false ,而我的活动却什么也没做。这是我的事件代码:

I'm trying to automatize some tasks in JavaScript and I need to use a InputEvent, but when I use normal event, I'm getting event.isTrusted = false and my event is doing nothing. Here is my event code:

var event = new InputEvent('input', {
    bubbles: true,
    cancelable: false,
    data: "a"
}); 

document.getElementById('email').dispatchEvent(event);

此代码应将 a放入ID为 email的textField中,但当event.isTrusted = false时,此代码无所事事。我正在使用事件监听器断点在源代码标签中的Chrome开发者工具中对其进行测试(我仅检查了键盘>输入断点,并向我显示了所用事件的所有属性)。
我检查了真正的键盘单击的所有属性,唯一不同的是event.isTrusted。

This code should put "a" into a textField with id "email", but when event.isTrusted = false, this code is doing nothing. I'm testing it in Chrome Developer Tools in Sources tab with Event Listener Breakpoints (I checked only keyboard>input breakpoint and it shows me all attributes of used event). I checked all attributes from real keyboard click and only thing that is different is event.isTrusted.

我可以更改什么或可以做些什么来获得事件。 isTrusted = true

What can I change or what can I do to get event.isTrusted = true?

推荐答案


Event接口的isTrusted只读属性是一个布尔值,当事件由用户操作生成时为 true ,而当事件由脚本创建或修改或通过dispatchEvent派发时为 false。

The isTrusted read-only property of the Event interface is a boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via dispatchEvent.

来源: MDN

您可能误解了输入事件,在用户在输入中输入会触发该事件。手动触发事件不会使输入更改其值,而是更改值会使输入触发事件而并非相反。

You may have misunderstood the concept of the Input Event, the event is triggered after the user type in the input. Manually triggering the event will not make the inputs change their values, is the changing of the values that makes the input trigger's the event not the opposite.

如果您真的想通过自定义事件更改输入的值,则可以执行以下操作:

If you really want to change the value of the inputs with a custom event you can do something like this:

let TargetInput = document.getElementById('target')
let Button = document.getElementById('btnTrigger');

Button.addEventListener('click',function(e){
    Trigger();
}, false);

TargetInput.addEventListener('input',function(e){
    if(!e.isTrusted){
		//Mannually triggered
		this.value += e.data;
	}
}, false);

function Trigger(){
	var event = new InputEvent('input', {
		bubbles: true,
		cancelable: false,
		data: "a"
	}); 

	TargetInput.dispatchEvent(event);
}

Target: <input type="text" id="target">

<hr>

<button id="btnTrigger">Trigger Event</button>

这篇关于JavaScript触发InputEvent.isTrusted = true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆