As of Chrome 53, how to add text as if a trusted textInput event was dispatched?

时光怂恿深爱的人放手 提交于 2019-12-18 09:17:22

问题


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

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);

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

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.

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


回答1:


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/



来源:https://stackoverflow.com/questions/39947875/as-of-chrome-53-how-to-add-text-as-if-a-trusted-textinput-event-was-dispatched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!