Search code examples
tinymcefocusexeccommand

TinyMCE steals the focus when calling execCommand


I have a bunch of inputs on my HTML page, plus a textarea which is replaced by a TinyMCE editor. There are various scenarios where this page is loaded and every time one of the inputs must get the focus. But when the TinyMCE is initialized, it just steals the focus. I narrowed down the problem to an execCommand call which sets the default font size in TinyMCE.

The issue can be reproduced in this simplified code:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
        <script>
            tinymce.init({
                selector: 'textarea',
                setup: function(editor) {
                    editor.on('init', function() {
                        this.execCommand("fontSize", false, "14pt"); // <<---- This line causes the TinyMCE editor to steal the focus!
                    });
                }
            });
        </script>
    </head>

    <body>
        <input id="inp" />
        <textarea>Hello, World!</textarea>
        
        <script>
            document.getElementById("inp").focus();
        </script>
    </body>
</html>

I have tested this in Firefox, Chrome, and Edge, and the same issue happened in all of them. Any idea how I can prevent this? I do not want to set the focus again once the TinyMCE is done initializing, since at that point the page has scrolled to the wrong spot.


Solution

  • I know I said I did not want to set the focus "again" once the TinyMCE is done initialization, but I ended up doing something similar to that. Instead of setting the focus at the bottom of the page, I moved the code inside the tinymce.init and also called $(document).scrollTop(0);. Here is the code:

    tinymce.init({
        selector: 'textarea',
        setup: function(editor) {
            editor.on('init', function() {
                this.execCommand("fontSize", false, "14pt"); // <<---- This line causes the TinyMCE editor to steal the focus!
                            
                // Scroll to the top of the page.
                $(document).scrollTop(0);
                // Now set the focus.
                document.getElementById("inp").focus();
            });
        }
    });
    

    I believe there is a bug in TinyMCE and I hope it gets fixed in one of the future revs. I also hope this workaround helps someone down the road.