iframe - 从 DOM 中删除并再次添加时,CKEditor 会丢失内容

标签 iframe ckeditor

上下文

CKEditor是一个富文本编辑器,使用带有可编辑正文的 iframe。

我遇到了一种情况,我需要暂时从页面中删除包含 CKEditor 实例的元素,然后在稍后任意时间将其添加回来。

问题

不幸的是,这似乎会导致 iframe 重置。编辑器最初包含富文本内容和可编辑的正文元素,将编辑器添加回页面后,iframe 正文为空且不再可编辑。

问题

我希望有人能够解释为什么会发生这种情况,以及在将 CKEditor 添加回 DOM 后如何重新初始化它。我已经搜索了文档,但尚未找到答案。

销毁实例并重新创建是可能的,但这需要对我们的架构进行一些重大更改。如果可能的话,我宁愿避免这种情况。 (尽管“没有其他选择”是一个可以接受的答案,如果是的话。)

示例

这是我的代码的极其简化的版本,它重现了问题:

CKEDITOR.replace('text');

var wrapper = $("#wrapper"),
    parent = $("#parent");

// Immediately after creating the CKEditor instance,
// it is possible to remove and append the editor
hideshow();

// Remove and append some moments after the page load causes
// the content of the CKEditor to be lost (and not editable)
$('#hideshow').click(hideshow);
// (I'm guessing this is because the click event happens
// sometime after the editor is initialized.)

function hideshow(){
    wrapper.remove();
    parent.append(wrapper);
}

http://jsfiddle.net/cyborgx37/f496p7us/

我可以在上面的 hideshow 函数中添加什么来恢复编辑器的内容?

最佳答案

I'm hoping someone can explain why this is happening and how I can reinitialize the CKEditor once I've added it back to the DOM. I've searched the documentation and have yet to find an answer.

Destroying the instance and re-creating is possible, but it's going to require some significant changes to our architecture. I'd rather avoid that, if possible. (Though "there's no other option" is an acceptable answer, if true.)

答案是,如果你想使用 iframed 编辑器,没有其他选择。在这种情况下,必须重新初始化编辑器。

iframe 内容消失的原因与 CKEditor 无关 – 这纯粹是浏览器行为。理论上,CKEditor 可能会监听某些 unload 事件并缓存数据(如果当时可能的话),以便可以在某个时刻恢复它们。然而,这会非常复杂,所以核心插件不会这样做。您可以尝试编写一个插件来增强 wysiwygarea 插件,但这可能很棘手。

因此,如果您想继续使用 iframed 编辑器,那么手动重新初始化似乎是最简单的选择。

另一个选项是使用 divarea插件使 CKEditor 使用简单的 div 而不是 iframe。这有一些优点,例如卸载没有问题并且通常更轻,但当然可能更难设置编辑器内容的样式。

关于iframe - 从 DOM 中删除并再次添加时,CKEditor 会丢失内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494039/

相关文章:

javascript - AngularJS Controller 如何访问非 AngularJS iframe 中的函数?

html - iframe 在容器内居中并停止调整大小

javascript - Firefox 无法访问同一域上的 iframe 打印

asp.net-mvc-4 - ckeditor.js :219 Uncaught TypeError: Cannot set property 'dir' of undefined

javascript - 如何在 Laravel 中从服务器发送 javascript 响应而不转义字符

widget - 如何在自定义 CKEditor 小部件中使 a 标签可编辑?

YouTube iframe 的 JavaScript 播放/暂停按钮

javascript - 可以跨 iframe 共享 javascript 导入吗?

javascript - REACTJS - 从在线构建导入 CKEditor 5

textarea - Cckeditor 更新文本区域