简体   繁体   中英

Can Firefox use document.execCommand in a textarea?

With the cursor in a contenteditable div , both Chrome and Firefox can emulate typing "sometext" like this:

document.execCommand('insertText', false, 'sometext');

In Chrome, this works when you're in a textarea as well. In Firefox, I get the error "NS_ERROR_FAILURE:".

Here's a fiddle to demonstrate: http://jsfiddle.net/ukx37/ . In Chrome, hit enter and you type "ENTER\\n". In Firefox, you type "\\n" and get an error NS_ERROR_FAILURE.

Does anybody know if there's a way to get this working in Firefox? Or, if not, is there some way I can test for support without a try-catch statement?

Also, I don't want to manually edit the textarea's value because doing so breaks the edit history.

Figured out that the error is being fired because the focused Node isn't contentEditable. If you make the textarea contentEditable it stops firing errors, but gets all buggy. Firefox will sometimes put the inserted text in the textarea, sometimes put it in the DOM as a child node of the textarea (and never display it), sometimes do nothing. No errors are fired, but it's still unusable. Same thing for making a parent contentEditable and the textarea not.

The answer I'm using for now is feature-detecting and giving up if it doesn't "just work". If somebody gets Firefox to work I'll un-accept this and accept theirs. Until then, here's the code I'm using.

var canEditInput = (function () {
    try {
        var t = document.createElement('textarea');
        document.body.appendChild(t);
        t.focus();
        document.execCommand('insertText', false, 'x');
        document.body.removeChild(t);
        return t.value === 'x';
    } catch (e) {
        return false;
    }
})();

Note that we can't give t display:none; because then it can't be focused. But it shouldn't matter, because the JS should finish (and remove t ) before the browser starts to draw the next frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM