Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...