Alex-D / Trumbowyg

A lightweight and amazing WYSIWYG JavaScript editor under 10kB
https://alex-d.github.io/Trumbowyg
MIT License
3.96k stars 606 forks source link

Retrieving HTML sometimes returns empty string if the editor node wasn't visible and the user hasn't clicked on/engaged with the editor yet. #1419

Open madelson opened 10 months ago

madelson commented 10 months ago

First off, thanks for this fantastic library!

One thing I ran into while testing which stumped me for a bit is that sometimes I was getting empty string back from .trumbowyg('html') even though the editor was clearly on screen populated with lots of text.

Description

On my page, the user clicks an "edit" button which copies the html from another page element into the editor node and then shows the editor. The user can then hit "save" to copy the html back. This was breaking because if the user hit "save" without engaging with the editor, it would give empty string for it's HTML.

OS: Windows 11 Browser: Chrome 116.0.5845.111

How to reproduce?

For me, copying the below into a .html file, opening in chrome, and clicking the button reproduces the issue:

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Trumbowyg/2.27.3/trumbowyg.min.js" integrity="sha512-YJgZG+6o3xSc0k5wv774GS+W1gx0vuSI/kr0E0UylL/Qg/noNspPtYwHPN9q6n59CTR/uhgXfjDXLTRI+uIryg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Trumbowyg/2.27.3/ui/trumbowyg.min.css" integrity="sha512-Fm8kRNVGCBZn0sPmwJbVXlqfJmPC13zRsMElZenX6v721g/H7OukJd8XzDEBRQ2FSATK8xNF9UYvzsCtUpfeJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    </head>
    <body>
        <div id="container" style="display: none;">
            <div id="editor"></div>
        </div>
        <button id="b">click</button>
        <script>
            $(document).ready(function () {
                var editor = $('#editor');
                editor.trumbowyg();
                $('#b').click(function () {
                    editor.html('some text');
                    $('#container').show();
                    // gives empty string until the user clicks on the editor
                    console.log("HTML = " + editor.trumbowyg('html'));
                })
            });
        </script>
    </body>
</html>
Alex-D commented 9 months ago

Hi

You must use Trumbowyg API to ensure that content is loaded as expected.

See documentation here: https://alex-d.github.io/Trumbowyg/documentation/#manage-content

Hope it helps :)