从Chrome 53开始,如何添加文本,就好像发送了可信的textInput事件一样? [英] As of Chrome 53, how to add text as if a trusted textInput event was dispatched?

查看:275
本文介绍了从Chrome 53开始,如何添加文本,就好像发送了可信的textInput事件一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自Chrome 53开始,不受信任的事件不再调用默认操作。 https://developer.mozilla.org/en-US/docs / Web / API / Event / isTrusted

As of Chrome 53, untrusted events no longer invoke the default action. https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted

在Chrome 53之前,此JavaScript会添加一个interrobang,‽。

Before Chrome 53, this JavaScript would add an interrobang, ‽.

var e = document.createEvent('TextEvent');
e.initTextEvent('textInput',
                true,
                true,
                null,
                String.fromCharCode( 8253 ));
document.activeElement.dispatchEvent(e);

在Chrome 53中,看看会发生什么: https://jsfiddle.net/dblume/2nfhrj1j/10/

In Chrome 53, see what happens: https://jsfiddle.net/dblume/2nfhrj1j/10/

而且createEvent()不受信任,它不会像在Chrome 52和之前那样获得由activeElement处理的数据。

Since the event made with createEvent() is untrusted, it doesn't get its data processed by the activeElement like it did in Chrome 52 and before.

我的Chrome扩展程序在Chrome中停止运行因为它试图分派这样的textInput事件。现在该怎么办?

My Chrome extension stopped working as of Chrome 53 because it tried to dispatch such a textInput event. What should it do instead now?

推荐答案

切换到 document.execCommand 它可以在任何文本元素以及任何带有 contenteditable =true的元素中生成并生成可信的input事件。将文本插入插入位置(如果有,则替换选择),就像用户键入一样。与 TextEvent 事件相比,唯一的缺点是input事件不包含插入的文本。

Switch to document.execCommand that works in any text element as well as any element with contenteditable="true" and generates a trusted "input" event. The text is inserted at the caret position (replacing selection if any) just as if it was typed by a user. The only drawback compared to TextEvent event is that "input" event doesn't contain the inserted text.

document.execCommand('insertText', false, String.fromCharCode(8253));
document.execCommand('insertHTML', false, '‽'); // the same

https://jsfiddle.net/2nfhrj1j/22/

这篇关于从Chrome 53开始,如何添加文本,就好像发送了可信的textInput事件一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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