Skip to main content

init()

Initializes a new OnlyOffice editor instance in the specified container.

Signature

OnlyOfficeEditorModule.init(containerId, config, options)

Parameters

containerId
string
required
The ID of the DOM element that will host the editor iframe. The element must exist in the DOM before calling this method.
config
object
required
OnlyOffice Document Server configuration object. Must include at minimum document.url.
{
  document: {
    fileType: 'docx',
    key: 'unique-key',
    title: 'Document.docx',
    url: 'https://example.com/doc.docx'
  },
  documentType: 'word',
  editorConfig: { /* optional */ }
}
options
object
Optional callbacks and configuration.

Returns

return
DocEditor | null
Returns the OnlyOffice DocEditor instance if successful, or null if initialization failed (e.g., invalid config or DocsAPI not loaded).

Behavior

  • If an editor already exists for the given containerId, it will be destroyed first
  • Sets default customization options if not provided
  • Shows a loading indicator during initialization
  • Automatically hides loading indicator after 8 seconds as fallback

Default Customization

The following defaults are applied if not specified in config.editorConfig.customization:
PropertyDefault Value
uiTheme'theme-classic-light'
compactToolbarfalse
toolbarNoTabsfalse
hideRightMenutrue
hideRulerstrue
review.showReviewChangesfalse

Example

var config = {
    document: {
        fileType: 'xlsx',
        key: 'spreadsheet-123',
        title: 'Sales Report.xlsx',
        url: 'https://example.com/sales.xlsx'
    },
    documentType: 'cell',
    editorConfig: {
        mode: 'edit',
        customization: {
            uiTheme: 'theme-dark',
            compactToolbar: true
        }
    }
};

var options = {
    onReady: function() {
        console.log('Editor initialized');
    },
    onDocumentReady: function() {
        console.log('Document loaded');
    },
    onError: function(evt) {
        console.error('Editor error:', evt.data);
        alert('Failed to load editor');
    }
};

var editor = OnlyOfficeEditorModule.init('editorContainer', config, options);

if (editor) {
    console.log('Editor created successfully');
} else {
    console.error('Failed to create editor');
}
The config.document.url must be accessible from the OnlyOffice Document Server. Make sure CORS and network policies allow access.

getEditedDocumentUrl()

Retrieves the download URL for the edited document from OnlyOffice Document Server.

Signature

OnlyOfficeEditorModule.getEditedDocumentUrl(containerId)

Parameters

containerId
string
required
The ID of the editor container.

Returns

return
Promise<string>
A Promise that resolves with the download URL string, or rejects with an error.

Behavior

  • Triggers the downloadAs() method on the OnlyOffice editor
  • Shows loading indicator during the operation
  • Waits for the onDownloadAs event from OnlyOffice
  • Has a 30-second timeout
  • Rejects if editor is not initialized

Example

OnlyOfficeEditorModule.getEditedDocumentUrl('editorContainer')
    .then(function(url) {
        console.log('Document URL:', url);
        // Download the file
        window.location.href = url;
    })
    .catch(function(error) {
        console.error('Failed to get document URL:', error);
        alert('Could not retrieve document');
    });

With Async/Await

async function downloadDocument() {
    try {
        var url = await OnlyOfficeEditorModule.getEditedDocumentUrl('editorContainer');
        console.log('Document available at:', url);
        return url;
    } catch (error) {
        console.error('Download failed:', error);
        throw error;
    }
}
This method triggers a server-side conversion/save operation in OnlyOffice Document Server. The URL is temporary and typically expires after a short period.

getEditedDocumentBlob()

Retrieves the edited document as a Blob object, ready for upload or processing.

Signature

OnlyOfficeEditorModule.getEditedDocumentBlob(containerId)

Parameters

containerId
string
required
The ID of the editor container.

Returns

return
Promise<Blob>
A Promise that resolves with a Blob object containing the document binary data, or rejects with an error.

Behavior

  • First calls getEditedDocumentUrl() to get the download URL
  • Fetches the document content using the Fetch API
  • Returns the response as a Blob
  • Supports proxy URL configuration via window.__onlyOfficeProxyUrl

Proxy Support

If window.__onlyOfficeProxyUrl is defined, the module will route the download through a proxy:
// Set proxy before calling getEditedDocumentBlob
window.__onlyOfficeProxyUrl = '/api/proxy?url=';

OnlyOfficeEditorModule.getEditedDocumentBlob('editorContainer')
    .then(function(blob) {
        console.log('Document blob size:', blob.size, 'bytes');
    });

Example: Save to Disk

OnlyOfficeEditorModule.getEditedDocumentBlob('editorContainer')
    .then(function(blob) {
        // Create download link
        var url = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'edited-document.docx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    })
    .catch(function(error) {
        console.error('Failed to get document blob:', error);
    });

Example: Upload via FormData

async function uploadEditedDocument() {
    try {
        var blob = await OnlyOfficeEditorModule.getEditedDocumentBlob('editorContainer');
        
        var formData = new FormData();
        formData.append('file', blob, 'document.docx');
        
        var response = await fetch('/api/documents/upload', {
            method: 'POST',
            body: formData
        });
        
        if (response.ok) {
            console.log('Document uploaded successfully');
        }
    } catch (error) {
        console.error('Upload failed:', error);
    }
}
Use getEditedDocumentBlob() instead of getEditedDocumentUrl() when you need to process the document content in JavaScript or upload it to your server.

captureToHiddenField()

Captures the edited document and stores it as base64-encoded data in a hidden form field. Optionally triggers ASP.NET postback.

Signature

OnlyOfficeEditorModule.captureToHiddenField(containerId, hiddenFieldId, options)

Parameters

containerId
string
required
The ID of the editor container.
hiddenFieldId
string
required
The ID of the hidden input field where the base64 data will be stored.
options
object
Optional configuration for the capture operation.

Returns

return
Promise<string>
A Promise that resolves with the base64-encoded document string, or rejects with an error.

Behavior

  1. Calls getEditedDocumentBlob() to retrieve the document
  2. Converts the Blob to base64 using FileReader
  3. Sets the value of the hidden field to the base64 string
  4. Optionally triggers postback and destroys the editor
  5. Disables beforeunload warnings if postback is triggered

Example: Basic Capture

<input type="hidden" id="hdnDocument" runat="server" />
OnlyOfficeEditorModule.captureToHiddenField('editorContainer', 'hdnDocument', {
    onCaptured: function(base64) {
        console.log('Document captured, size:', base64.length, 'characters');
        alert('Document saved!');
    },
    onError: function(error) {
        console.error('Capture failed:', error);
        alert('Failed to save document');
    }
});

Example: With ASP.NET Postback

function saveDocument() {
    OnlyOfficeEditorModule.captureToHiddenField(
        'editorContainer',
        '<%= hdnDocumentContent.ClientID %>',
        {
            autoPostBack: true,
            postBackTarget: '<%= btnSave.UniqueID %>',
            postBackArgument: '',
            onCaptured: function(base64) {
                console.log('Triggering postback...');
            },
            onError: function(error) {
                alert('Error: ' + error.message);
            }
        }
    );
}

Server-Side (ASP.NET)

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        string base64Content = hdnDocumentContent.Value;
        if (!string.IsNullOrEmpty(base64Content))
        {
            byte[] documentBytes = Convert.FromBase64String(base64Content);
            // Save to database, file system, etc.
            SaveDocument(documentBytes);
        }
    }
}
Base64 encoding increases the data size by approximately 33%. Large documents may exceed POST size limits. Consider using getEditedDocumentBlob() with AJAX for larger files.
When autoPostBack is true, the editor instance is automatically destroyed before postback to prevent confirmation dialogs.

getEditor()

Retrieves the underlying OnlyOffice DocEditor instance for advanced operations.

Signature

OnlyOfficeEditorModule.getEditor(containerId)

Parameters

containerId
string
required
The ID of the editor container.

Returns

return
DocEditor | null
The OnlyOffice DocEditor instance, or null if not found or not initialized.

Example

var editor = OnlyOfficeEditorModule.getEditor('editorContainer');

if (editor) {
    // Call native OnlyOffice API methods
    editor.showMessage('Hello from custom code!');
    
    // Request specific save operation
    editor.processSaveResult(true);
} else {
    console.error('Editor not found');
}

Use Cases

Custom Commands

Execute OnlyOffice Document Server API commands not wrapped by the module.

Advanced Integration

Access internal editor methods for complex customization.

Event Subscription

Subscribe to additional OnlyOffice events after initialization.

Plugin Management

Load or interact with OnlyOffice plugins programmatically.
Refer to the OnlyOffice API Documentation for available methods on the DocEditor object.

destroy()

Destroys an editor instance and releases resources.

Signature

OnlyOfficeEditorModule.destroy(containerId)

Parameters

containerId
string
required
The ID of the editor container to destroy.

Returns

return
void
This method does not return a value.

Behavior

  • Calls destroyEditor() on the OnlyOffice editor instance
  • Removes internal references to prevent memory leaks
  • Safe to call even if editor doesn’t exist (no-op)
  • Clears any pending download resolvers

Example

// Clean up when navigating away
window.addEventListener('beforeunload', function() {
    OnlyOfficeEditorModule.destroy('editorContainer');
});

Example: Reinitialize Editor

function reinitializeEditor() {
    // Destroy existing instance
    OnlyOfficeEditorModule.destroy('editorContainer');
    
    // Create new instance with different config
    var newConfig = {
        document: {
            fileType: 'docx',
            key: 'new-key-' + Date.now(),
            title: 'New Document.docx',
            url: 'https://example.com/new-doc.docx'
        },
        documentType: 'word'
    };
    
    OnlyOfficeEditorModule.init('editorContainer', newConfig);
}
destroy() is automatically called by init() if an editor already exists for the container, so you typically don’t need to call it manually before reinitializing.

Memory Management

// Good practice: destroy editors when done
function cleanupEditors() {
    var editorIds = ['editor1', 'editor2', 'editor3'];
    editorIds.forEach(function(id) {
        OnlyOfficeEditorModule.destroy(id);
    });
}

// Call on page unload or component unmount
window.addEventListener('pagehide', cleanupEditors);

Error Handling

All asynchronous methods return Promises and should include proper error handling:
// Using .catch()
OnlyOfficeEditorModule.getEditedDocumentUrl('editorContainer')
    .then(function(url) {
        console.log('Success:', url);
    })
    .catch(function(error) {
        console.error('Error:', error.message);
    });

// Using try/catch with async/await
async function handleDocument() {
    try {
        var blob = await OnlyOfficeEditorModule.getEditedDocumentBlob('editorContainer');
        // Process blob
    } catch (error) {
        console.error('Failed:', error);
        // Handle error
    }
}

Common Error Scenarios

ErrorCauseSolution
”Editor no inicializado”Editor not initialized or wrong container IDVerify containerId and ensure init() was called successfully
”DocsAPI not loaded”OnlyOffice API script not loadedLoad the OnlyOffice API script before initializing
”No se recibió URL de descarga”OnlyOffice didn’t return download URLCheck OnlyOffice server status and document key validity
”HiddenField no encontrado”Hidden field ID doesn’t existVerify the hidden field exists in the DOM

Build docs developers (and LLMs) love