如何借助 Playground 掌握 ONLYOFFICE API
若每次小型测试都需要搭建完整的插件或自动化环境,测试和探索 ONLYOFFICE API 往往面临较大挑战。ONLYOFFICE 文档 API Playground 为此提供了一个专门的实验环境,开发者能够通过代码与文档进行交互、测试指令并观察API的实时响应。
本指南将展示如何通过 Playground 加速开发进程,结合实用示例进行说明,并帮助您准确选择适合需求的 API。
Playground 的重要性
Playground 专为满足开发者以下需求而设计:
- 在实时编辑器环境中测试各类 API
- 通过编程方式插入和编辑文本或 HTML 内容
- 监听并响应文档事件
- 无需搭建完整插件或连接器环境,即可测试边界场景、大型输入或特殊字符
在构建插件或自动化流程前使用 Playground,能够帮助您提前发现潜在问题、掌握 API 特性,从而优化开发效率。
认识核心 API
Playground 支持三大主要 API:
- Office JavaScript API – 直接构建和操作文档,最适合脚本编写、文档生成及简单自动化任务
- 插件 API – 用于开发交互式 ONLYOFFICE 插件,支持 async/await 模式,简化代码执行流程并支持复杂操作
- 自动化 API / 连接器 – 供外部系统访问和修改文档,通过回调机制实现集成与自动化
每个 API 都有其特定应用场景,Playground 支持并行测试,帮助您选择最适合工作流程的方案。
Playground 代码片段实践
以下是一组实用示例,展示如何使用各 API。将代码复制到 Playground 编辑器中即可立即运行。
基础文本插入
用途:演示如何通过三种 API 在当前光标位置插入文本
场景:在文档中添加简单文本或测试 API 行为
//APPROACH 1: Using Automation API (Connector)
// Use this when working with connector for external document access
connector.executeMethod(
"PasteText",
["Hello from ONLYOFFICE Automation API!"],
function() {
console.log("Text inserted using Automation API");
}
);
//APPROACH 2: Using Plugin API with Editor helper
// Use this when developing plugins
(async function(){
await Editor.callMethod("PasteText", ["Hello from ONLYOFFICE Plugin API!"]);
console.log("Text inserted using Plugin API");
})();
//APPROACH 3: Using Office JavaScript API directly
// Use this for direct document building and manipulation
var oDocument = Api.GetDocument();
var oParagraph = Api.CreateParagraph();
oParagraph.AddText("Hello from ONLYOFFICE Office JavaScript API!");
oDocument.InsertContent([oParagraph]);
console.log("Text inserted using Office JavaScript API");
开发提示:调用方法后请立即查看控制台响应。即使是 PasteText 或 PasteHtml 这类简单操作,其行为也会受光标位置、选中内容或 HTML 结构影响。记录结果有助于及时发现异常行为。
格式化 HTML 内容
用途:演示如何插入包含标题、列表和自定义样式的富 HTML 内容
场景:导入格式内容、粘贴富文本或动态生成文档片段
// HTML string with various formatting elements
const htmlContent = `
<h2 style="color: #2E86C1;">Welcome to ONLYOFFICE</h2>
<p>This is a <strong>bold text</strong> and this is <em>italic text</em>.</p>
<ul>
<li>First bullet point</li>
<li>Second bullet point with <u>underlined text</u></li>
<li>Third bullet point</li>
</ul>
<p style="color: #28B463;">This paragraph has custom color styling.</p>
`;
// APPROACH 1: Using Automation API (Connector)
// The PasteHtml method automatically converts HTML to document elements
connector.executeMethod(
"PasteHtml",
[htmlContent],
function() {
console.log("HTML content inserted using Automation API");
}
);
// APPROACH 2: Using Plugin API with Editor helper
(async function(){
await Editor.callMethod("PasteHtml", [htmlContent]);
console.log("HTML content inserted using Plugin API");
})();
文档变更事件监听
用途:演示如何监听文档事件(如选中区域变更或内容更新)
场景:构建响应式功能、追踪用户操作或与外部系统同步
connector.attachEvent("onSelectionChanged", function(selectionInfo) {
console.log("Selection changed:", JSON.stringify(selectionInfo, null, 2));
// Get the current word under cursor
connector.executeMethod("GetCurrentWord", [], function(currentWord) {
console.log("Current word:", currentWord);
});
});
connector.attachEvent("onDocumentContentReady", function() {
console.log("Document ready");
});
// APPROACH 2: Using Plugin API
// Event listeners work similarly with Asc.plugin.attachEvent()
Asc.plugin.attachEvent("onSelectionChanged", function(selectionInfo) {
console.log("Selection changed:", JSON.stringify(selectionInfo, null, 2));
});
(async function(){
let word = await Editor.callMethod("GetCurrentWord");
console.log("Current word:", word);
})();
复杂嵌套 HTML 内容
用途:测试对含嵌套元素和表格的复杂 HTML 结构的处理能力
场景:生成报表、迁移格式文档或创建高级版式
const complexHtml = `
<h1 style="color: #2C3E50; text-align: center;">Comprehensive Document Report</h1>
<h2 style="color: #E74C3C;">1. Executive Summary</h2>
<p>This report demonstrates the ONLYOFFICE API's capability to handle
<em>complex HTML structures</em> with <u>multiple levels of nesting</u>.</p>
<h2 style="color: #E74C3C;">2. Key Features</h2>
<ul>
<li>Rich Text Formatting: Bold, italic, underline, and colors</li>
<li>Hierarchical Lists: Nested bullet points
<ul>
<li>Sub-item level 1</li>
<li>Sub-item level 2
<ul>
<li>Sub-item level 3 (deeply nested)</li>
</ul>
</li>
</ul>
</li>
<li>Tables and Structures: Complex layouts</li>
</ul>
<h2 style="color: #E74C3C;">3. Data Presentation</h2>
<table border="1" cellpadding="10" style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background-color: #3498DB; color: white;">
<th>Feature</th>
<th>Description</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text Insertion</td>
<td>Insert plain and formatted text</td>
<td style="color: #27AE60;">✓ Supported</td>
</tr>
<tr>
<td>HTML Import</td>
<td>Convert HTML to document elements</td>
<td style="color: #27AE60;">✓ Supported</td>
</tr>
<tr>
<td>Event Handling</td>
<td>Monitor document changes</td>
<td style="color: #27AE60;">✓ Supported</td>
</tr>
</tbody>
</table>
<h2 style="color: #E74C3C;">4. Conclusion</h2>
<p style=" padding: 15px;">
The ONLYOFFICE API successfully handles
<span style="background-color: #F39C12; color: white; padding: 2px 5px;">
complex HTML content</span> with multiple levels of nesting.
</p>
`;
// APPROACH 1: Using Automation API (Connector)
connector.executeMethod(
"PasteHtml",
[complexHtml],
function() {
console.log("Complex HTML inserted (" + complexHtml.length + " characters)");
}
);
// APPROACH 2: Using Plugin API with Editor helper
(async function(){
await Editor.callMethod("PasteHtml", [complexHtml]);
console.log("Complex HTML inserted using Plugin API");
})();
包含边界场景的首次 API 调用
用途:帮助初学者掌握 API 基础用法、常见边界场景和错误处理模式
场景:学习 Office JavaScript API、插件 API 与自动化 API 的核心概念
// APPROACH 1: Office JavaScript API
var oDocument = Api.GetDocument();
var oParagraph = Api.CreateParagraph();
oParagraph.AddText(" Hello from Office JavaScript API!");
oDocument.InsertContent([oParagraph]);
console.log("Content created with Office JavaScript API");
// EDGE CASE 1: Handling empty or null text
var oParagraph2 = Api.CreateParagraph();
var textToInsert = ""; // Empty string
if (textToInsert && textToInsert.trim().length > 0) {
oParagraph2.AddText(textToInsert);
} else {
oParagraph2.AddText("(Empty text was provided)");
}
oDocument.InsertContent([oParagraph2]);
// EDGE CASE 2: Working with special characters and Unicode
var oParagraph3 = Api.CreateParagraph();
oParagraph3.AddText("Special chars: © ® ™ € £ ¥ • · « » — 'quotes' 中文 العربية");
oDocument.InsertContent([oParagraph3]);
// EDGE CASE 3: Creating content with mixed formatting
var oParagraph4 = Api.CreateParagraph();
var oRun1 = Api.CreateRun();
oRun1.AddText("This is bold ");
oRun1.SetBold(true);
oParagraph4.AddElement(oRun1);
var oRun2 = Api.CreateRun();
oRun2.AddText("and this is italic ");
oRun2.SetItalic(true);
oParagraph4.AddElement(oRun2);
var oRun3 = Api.CreateRun();
oRun3.AddText("and this is colored.");
oRun3.SetColor(220, 20, 60, false); // Crimson color
oParagraph4.AddElement(oRun3);
oDocument.InsertContent([oParagraph4]);
// EDGE CASE 4: Checking if document exists before operations
if (oDocument) {
var oParagraph5 = Api.CreateParagraph();
oParagraph5.AddText("Document validation: OK");
oDocument.InsertContent([oParagraph5]);
console.log("Document exists and is accessible");
} else {
console.log("ERROR: Document not accessible");
}
// APPROACH 2: Plugin API with Editor Helper (For Plugin Development)
// Use async/await pattern with error handling
(async function(){
try {
// Get editor version
let version = await Editor.callMethod("GetVersion");
console.log("Editor version:", version);
// EDGE CASE 1: Insert HTML with error handling
await Editor.callMethod("PasteHtml", [
"<p><b>Hello</b> from <i>Plugin API</i>!</p>"
]);
console.log("Content inserted with Plugin API");
// EDGE CASE 2: Check if method returns undefined or null
let selectedText = await Editor.callMethod("GetSelectedText");
if (selectedText) {
console.log("Selected text:", selectedText);
} else {
console.log("No text selected or selection is empty");
}
// EDGE CASE 3: Handling special characters in Plugin API
await Editor.callMethod("PasteText", [
"Special: © 2024 | €100 | 中文"
]);
// EDGE CASE 4: Multiple async operations in sequence
await Editor.callMethod("PasteText", ["Line 1 "]);
await Editor.callMethod("PasteText", ["Line 2 "]);
await Editor.callMethod("PasteText", ["Line 3"]);
console.log("Multiple operations completed");
} catch (error) {
console.log("ERROR in Plugin API:", error.message || error);
}
})();
开发提示:使用 async/await 调用插件 API 时,请将调用语句包裹在 try/catch 块中。这能确保未定义选区或不支持内容等错误不会中断脚本执行,同时可通过控制台输出详细信息便于调试。
// APPROACH 3: Automation API (Connector - For External Access)
// Uses callbacks with error handling
// EDGE CASE 1: Check if connector exists before using
if (typeof connector !== 'undefined' && connector) {
// Basic text insertion with callback error handling
connector.executeMethod(
"PasteText",
["Hello from Automation API!"],
function(result) {
if (result !== undefined) {
console.log("Content inserted with Automation API");
} else {
console.log("Insert may have failed, result is undefined");
}
// EDGE CASE 2: Chain multiple operations with error checking
connector.executeMethod("GetCurrentWord", [], function(word) {
if (word && word.length > 0) {
console.log("Current word:", word);
} else {
console.log("No word at cursor position");
}
});
}
);
// EDGE CASE 3: Handling empty or invalid HTML
var htmlToInsert = "<p>Test</p>";
if (htmlToInsert && htmlToInsert.includes("<")) {
connector.executeMethod(
"PasteHtml",
[htmlToInsert],
function() {
console.log("HTML inserted successfully");
}
);
} else {
console.log("Invalid HTML content");
}
// EDGE CASE 4: Timeout handling for slow operations
var operationTimeout = setTimeout(function() {
console.log("WARNING: Operation taking longer than expected");
}, 5000);
connector.executeMethod(
"PasteText",
["Async operation test"],
function() {
clearTimeout(operationTimeout);
console.log("Operation completed in time");
}
);
} else {
console.log("ERROR: Connector is not available");
}
使用说明和实践
- 单独运行代码片段以避免冲突。
- 使用浏览器控制台查看执行日志和调试结果。
- 选择合适的 API:
从零开始构建文档 → Office JavaScript API,开发插件 → 插件 API,与外部应用程序集成 → 自动化 API(连接器)。
- 通过尝试不同的格式、HTML和事件,彻底了解API的行为。
推荐学习路径
- 从简单的首次 API 调用入手,对比不同方法的实现效果。
- 学习基础文本插入操作,掌握各 API 之间的核心区别。
- 测试 HTML 插入功能,实现格式化内容与富文本处理。
- 探索自动化 API 和插件 API 的事件监听机制。
- 进阶学习复杂 HTML 内容,掌握大型嵌套结构的处理方法。
总结
ONLYOFFICE Playground 作为一款功能强大的工具,能够显着加速 API 的学习、测试与插件开发进程。它提供了交互式沙盒环境,使开发者能够安全地进行实验,深入理解 API 的运行机制,从而更高效地构建稳健的插件与自动化工作流。
创建免费的 ONLYOFFICE 账户
在线查看并协作编辑文本文档、电子表格、幻灯片、表单和 PDF 文件。


