如何在TinyMCE中使用localStorage

时间:2017-01-02 16:25:47

标签: javascript jquery html5 tinymce local-storage

我试图找出如何在TinyMCE中使用localStorage。下面的脚本适用于textarea,但不支持启用TinyMCE。我不知道如何通过元素选择器获取编辑器实例。

HTML

<textarea id="editor"></textarea>
<p id="logs"></p>

JS

  (function() {
        try {
            (window.localStorage.getItem)
        } catch (e) {
            return
        }
        var area = document.querySelector('#editor');
        if (!area.value) {
            area.value = window.localStorage.getItem('value')
        }
        updateLog(false);
        document.querySelector('#editor').addEventListener('keyup', function() {
            window.localStorage.setItem('value', area.value);
            window.localStorage.setItem('timestamp', (new Date()).getTime());
            updateLog(true)
        }, false);

        function updateLog(new_save) {
            var log = document.querySelector("#logs");
            var delta = 0;
            if (window.localStorage.getItem('value')) {
                delta = ((new Date()).getTime() - (new Date()).setTime(window.localStorage.getItem('timestamp'))) / 1000;
                if (new_save) {
                    log.textContent = 'Saved.';
                    setTimeout(function() {
                        log.textContent = ''
                    }, 3000)
                } else {
                    log.textContent = 'last saved: ' + delta + 's ago'
                }
            }
        }
    })();

JSFiddle

1 个答案:

答案 0 :(得分:0)

我最终放弃了localStorage功能。最新版本的TinyMCE(v4.3)有一个自动保存插件。我在插件部分添加了autosave,在工具栏中添加了restoredraft,在tinymce.init中添加了autosave_interval: "1s"