Die ONLYOFFICE-APIs mit Playground meistern
Das Testen und Erkunden der ONLYOFFICE-APIs kann aufwendig sein, wenn für jedes kleine Experiment ein komplettes Plugin oder eine Automatisierungsumgebung eingerichtet werden muss. Der ONLYOFFICE Docs API Playground bietet eine spezielle Umgebung, in der Entwickler programmatisch mit Dokumenten interagieren, Befehle ausprobieren und das API-Verhalten in Echtzeit verstehen können.
In diesem Leitfaden zeigen wir Ihnen, wie der Playground die Entwicklung beschleunigt, stellen praktische Beispiele vor und geben Ihnen Hinweise zur Auswahl der passenden API für Ihre Bedürfnisse.

Warum der Playground wichtig ist
Der Playground wurde für Entwickler entwickelt, die:
- Mit verschiedenen APIs in einer Live-Editorumgebung experimentieren möchten.
- Programmgesteuert Text- oder HTML-Inhalte einfügen und bearbeiten möchten.
- Dokumentereignisse überwachen und darauf reagieren möchten.
- Grenzfälle, große Eingaben oder Sonderzeichen testen möchten, ohne eine vollständige Plugin- oder Konnektorumgebung einrichten zu müssen.
Die Verwendung des Playgrounds vor der Entwicklung eines Plugins oder Automatisierungs-Workflows hilft Ihnen, potenzielle Probleme frühzeitig zu erkennen, API-Beschränkungen zu verstehen und Ihren Entwicklungsprozess zu optimieren.
Verfügbare APIs verstehen
Der Playground unterstützt drei Haupt-APIs:
- Office JavaScript API – Direkte Dokumentenerstellung und -bearbeitung, ideal für Skripte, Dokumentengenerierung und einfache Automatisierungsaufgaben.
- Plugin API – Zur Entwicklung interaktiver ONLYOFFICE-Plugins. Unterstützt async/await-Muster für saubere Codeausführung und komplexe Operationen.
- Automation API / Connector – Ermöglicht externen Systemen den Zugriff auf und die Bearbeitung von Dokumenten mithilfe von Callbacks für Integration und Automatisierung.
Jede API erfüllt unterschiedliche Zwecke. Im Playground können Sie alle APIs direkt miteinander vergleichen, um die passende für Ihren Workflow zu finden.
Erste Schritte mit Playground-Codebeispielen
Im Folgenden finden Sie praktische Beispiele zur Verwendung der einzelnen APIs. Kopieren Sie ein Codebeispiel in den Playground-Editor, um es sofort auszuführen.
Einfaches Einfügen von Text
Zweck: Demonstration des Einfügens von Text an der aktuellen Cursorposition mithilfe aller drei APIs.
Anwendungsfall: Einfaches Einfügen von Text in Dokumente oder Testen des API-Verhaltens.
//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");
Entwicklertipp: Überprüfen Sie die API-Antwort immer sofort nach dem Aufruf einer Methode in der Konsole. Selbst einfache Operationen wie PasteText (Text einfügen) oder PasteHtml (HTML einfügen) können sich je nach Cursorposition, Auswahl oder HTML-Struktur unterschiedlich verhalten. Protokollierung der Ergebnisse hilft, unerwartetes Verhalten frühzeitig zu erkennen.
Formatierter HTML-Inhalt
Zweck: Zeigt, wie formatierter HTML-Inhalt, einschließlich Überschriften, Listen und benutzerdefinierter Formatierungen, eingefügt wird.
Anwendungsbeispiel: Formatierten Inhalt importieren, formatierten Text einfügen oder Abschnitte dynamisch generieren.
// 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");
})();
Ereignis-Listener für Dokumentänderungen
Zweck: Demonstration der Überwachung von Dokumentereignissen wie Auswahländerungen oder Inhaltsaktualisierungen.
Anwendungsfall: Entwicklung responsiver Funktionen, Nachverfolgung von Benutzeraktionen oder Synchronisierung mit externen Systemen.
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);
})();
Umfangreicher und verschachtelter HTML-Inhalt
Zweck: Testet die Verarbeitung komplexer HTML-Strukturen mit verschachtelten Elementen und Tabellen.
Anwendungsfall: Generieren von Berichten, Migrieren formatierter Dokumente oder Erstellen komplexer Layouts.
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");
})();
Einfacher erster API-Aufruf mit Sonderfällen
Zweck: Einführung in die API-Nutzung, häufige Sonderfälle und Fehlerbehandlungsmuster für Anfänger.
Anwendungsfall: Erlernen der Grundlagen der Office JavaScript API, der Plugin API und der Automatisierungs-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);
}
})();
Entwicklertipp: Bei der Verwendung der Plugin-API mit async/await sollten Sie Ihre Aufrufe in try/catch-Blöcke einschließen. Dadurch wird verhindert, dass Fehler wie undefinierte Auswahlen oder nicht unterstützte Inhalte Ihr Skript zum Absturz bringen, und Sie können aussagekräftige Konsolenmeldungen zur Fehlersuche ausgeben.
// 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");
}
Anwendungshinweise und Best Practices
- Führen Sie Code-Snippets einzeln aus, um Konflikte zu vermeiden.
- Verwenden Sie die Browserkonsole, um Ausführungsprotokolle und Debugging-Ergebnisse anzuzeigen.
- Wählen Sie die passende API:
Dokumente von Grund auf neu erstellen → Office JavaScript API,
Plugins entwickeln → Plugin API,
Integration mit externen Anwendungen → Automation API (Connector).
- Experimentieren Sie mit Formatierung, HTML und Ereignissen, um das API-Verhalten vollständig zu verstehen.
Empfohlener Lernpfad
- Beginnen Sie mit dem einfachen ersten API-Aufruf, um die verschiedenen Ansätze zu vergleichen.
- Fahren Sie mit dem Einfügen von einfachem Text fort, um die Unterschiede zwischen den APIs zu verstehen.
- Testen Sie das Einfügen von HTML-Code für Formatierung und Rich Content.
- Erkunden Sie die Ereignis-Listener für Automatisierungs- und Plugin-APIs.
- Gehen Sie zu komplexen HTML-Inhalten über, um große, verschachtelte Strukturen zu verarbeiten.
Fazit
Der ONLYOFFICE Playground ist ein leistungsstarkes Tool, um das Erlernen, Testen und Entwickeln von APIs zu beschleunigen. Durch die Bereitstellung einer interaktiven Sandbox-Umgebung können Entwickler sicher experimentieren, das API-Verhalten eingehend verstehen und robuste Plugins sowie Automatisierungs-Workflows effizienter erstellen.
Erstellen Sie Ihr kostenloses ONLYOFFICE-Konto
Öffnen und bearbeiten Sie gemeinsam Dokumente, Tabellen, Folien, Formulare und PDF-Dateien online.


