业务页面里,用户打开编辑器编辑文档后会关闭编辑器。很多页面关闭时只是把编辑器从页面上删掉。编辑器虽然看不见了,但它在后台留下的一些处理还在运行。反复打开关闭后,旧的处理可能还在响应新文档的操作,页面也会越来越卡。只要编辑器不再使用,就应该用 destroyEditor 清理。本文以 Word 为例,说明如何销毁 Spire.OfficeJS 编辑器。
销毁流程
销毁编辑器可以概括为三步:打开编辑器、调用 destroyEditor()、页面恢复原样。

- 用户打开编辑器。
OpenApi会在业务页面上创建编辑器,原来的占位<div>被替换。 - 调用
destroyEditor()删除编辑器。它会解绑业务页面上的事件监听器和鼠标监听器,再把编辑器 iframe 替换回原来的占位<div>。 - 页面恢复到打开前的状态,占位
<div>重新出现。
调用方式
destroyEditor 不是全局方法,也不在编辑器 iframe 元素上,而是 new SpireCloudEditor.OpenApi() 返回对象上的方法。创建编辑器时要把这个返回值保存下来,销毁时再通过它调用。
示例代码:
var editor = new SpireCloudEditor.OpenApi('editor', config);
editor.destroyEditor();
editor = null;
注意
destroyEditor() 每个实例只能调用一次,重复销毁会报错。销毁成功后,把 editor 置空,避免继续使用已经失效的旧对象;需要再次打开时,重新创建实例。
完整示例
下面是一个完整示例代码:页面加载时创建编辑器并保存返回对象,点击“销毁编辑器”按钮时再调用 destroyEditor()。运行时把 LocalExample 替换成实际部署地址。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Spire.OfficeJS 销毁编辑器</title>
<style>
html, body { height: 100%; margin: 0; background-color: #cbe4f3;}
body { display: flex; flex-direction: column; }
#editor { flex: 1; min-height: 0; }
#editor iframe { width: 100%; height: 100%; border: 0; }
</style>
</head>
<body>
<button id="destroyBtn">销毁编辑器</button>
<div id="editor"></div>
<script src="http://LocalExample:3000/web/editors/spireapi/SpireCloudEditor.js"></script>
<script>
var SERVER = 'http://LocalExample:3000';
var config = {
fileAttrs: {
fileInfo: { name: 'sample.docx', ext: 'docx' },
sourceUrl: SERVER + '/samples/sample.docx'
},
user: { id: 'uid-1', name: 'Jonn' },
editorAttrs: {
editorMode: 'edit',
editorType: 'document',
viewLanguage: 'zh',
useWebAssemblyDoc: true,
spireOfficeJsLicense: '',
serverless: {
useServerless: true,
baseUrl: SERVER
}
}
};
var editor = new SpireCloudEditor.OpenApi('editor', config);
document.getElementById('destroyBtn').addEventListener('click', function () {
editor.destroyEditor();
editor = null;
});
</script>
</body>
</html>
打开文档并点击“销毁编辑器”按钮后,销毁编辑器:

注意
destroyEditor() 不保存文档,也不取消已经发出的保存、下载请求。需要保留修改时,先保存并等待完成,再销毁。
常见问题
销毁后容器样式变了
原因:销毁后恢复的占位 <div> 只设置了 id,原来的 class 和行内 style 不会恢复。
解决:把容器尺寸和样式写在 id 选择器里,例如 #editor { flex: 1; min-height: 0; }。
销毁后原来的 downloadAs 等方法还能用吗
原因:销毁时已经解绑了业务页面上的事件处理,返回对象收不到编辑器的响应。
解决:销毁后不要再使用返回对象上的其他方法。
销毁会清理 localStorage 或服务端缓存吗
原因:destroyEditor() 只处理业务页面上的收尾,不清理浏览器存储和服务端缓存。
解决:需要清理时,在业务系统里另行处理。







