API Reference
This document provides complete API reference for the Markdown to HTML Converter, including configuration options, methods, and integration examples.
Core API
convertMarkdown(markdown, options)
Converts Markdown text to HTML with specified options.
Parameters
markdown
(string, required)
- The Markdown text to convert
- Can be empty string
- Maximum length: 1MB
options
(object, optional)
- Configuration options for conversion
- Default values applied if not specified
Options Object
interface ConversionOptions {
outputFormat?: 'html' | 'xhtml';
encoding?: 'utf8' | 'ascii' | 'latin1';
sanitize?: boolean;
gfm?: boolean;
breaks?: boolean;
}
Option Details
outputFormat
(string, optional)
- Default:
'html'
- Values:
'html'
|'xhtml'
- Description: Output format for generated HTML
encoding
(string, optional)
- Default:
'utf8'
- Values:
'utf8'
|'ascii'
|'latin1'
- Description: Character encoding for output
sanitize
(boolean, optional)
- Default:
true
- Description: Enable HTML sanitization for security
gfm
(boolean, optional)
- Default:
true
- Description: Enable GitHub Flavored Markdown features
breaks
(boolean, optional)
- Default:
false
- Description: Convert line breaks to
<br>
tags
Return Value
Returns: Promise<string>
- Resolves to the converted HTML string
- Rejects with error if conversion fails
Example Usage
// Basic conversion
const html = await convertMarkdown('# Hello World');
// Advanced conversion with options
const html = await convertMarkdown(markdownText, {
outputFormat: 'xhtml',
encoding: 'utf8',
sanitize: true,
gfm: true,
breaks: false,
});
Utility Functions
sanitizeHtml(html)
Sanitizes HTML content by removing potentially dangerous elements.
Parameters
html
(string, required)
- HTML content to sanitize
Return Value
Returns: string
- Sanitized HTML with dangerous elements removed
Example
const cleanHtml = sanitizeHtml('<p>Safe content</p><script>alert("XSS")</script>');
// Returns: '<p>Safe content</p>'
validateUrl(url)
Validates URLs to ensure they use safe protocols.
Parameters
url
(string, required)
- URL to validate
Return Value
Returns: boolean
true
if URL is safe,false
otherwise
Example
validateUrl('https://example.com'); // true
validateUrl('javascript:alert(1)'); // false
Configuration API
setDefaultOptions(options)
Sets default options for all conversions.
Parameters
options
(object, required)
- Default options to apply
Example
setDefaultOptions({
outputFormat: 'xhtml',
sanitize: true,
gfm: true,
});
getDefaultOptions()
Retrieves current default options.
Return Value
Returns: object
- Current default options
Example
const defaults = getDefaultOptions();
console.log(defaults); // { outputFormat: 'html', sanitize: true, ... }
History API
addToHistory(record)
Adds a conversion record to history.
Parameters
record
(object, required)
interface HistoryRecord {
id: string;
title: string;
markdown: string;
html: string;
outputFormat: string;
encoding: string;
sanitize: boolean;
gfm: boolean;
breaks: boolean;
inputLength: number;
outputLength: number;
timestamp: number;
}
Example
addToHistory({
id: 'unique-id',
title: 'My Document',
markdown: '# Hello',
html: '<h1>Hello</h1>',
outputFormat: 'html',
encoding: 'utf8',
sanitize: true,
gfm: true,
breaks: false,
inputLength: 7,
outputLength: 13,
timestamp: Date.now(),
});
getHistory()
Retrieves conversion history.
Return Value
Returns: Array<HistoryRecord>
- Array of history records, sorted by timestamp (newest first)
clearHistory()
Clears all conversion history.
removeFromHistory(id)
Removes a specific record from history.
Parameters
id
(string, required)
- ID of the record to remove
Error Handling
Error Types
ConversionError
Thrown when Markdown conversion fails.
try {
const html = await convertMarkdown(invalidMarkdown);
} catch (error) {
if (error instanceof ConversionError) {
console.error('Conversion failed:', error.message);
}
}
ValidationError
Thrown when input validation fails.
try {
const html = await convertMarkdown('', { encoding: 'invalid' });
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
}
}
Error Properties
interface ConversionError {
name: string;
message: string;
code: string;
details?: any;
}
Browser Integration
Clipboard API
// Copy HTML to clipboard
async function copyToClipboard(html) {
try {
await navigator.clipboard.writeText(html);
console.log('HTML copied to clipboard');
} catch (error) {
console.error('Failed to copy:', error);
}
}
Download API
// Download HTML as file
function downloadHtml(html, filename = 'document.html') {
const blob = new Blob([html], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
Performance API
getPerformanceMetrics()
Returns performance metrics for the last conversion.
Return Value
interface PerformanceMetrics {
conversionTime: number; // Time in milliseconds
inputSize: number; // Input size in bytes
outputSize: number; // Output size in bytes
memoryUsage: number; // Memory usage in bytes
}
Example
const metrics = getPerformanceMetrics();
console.log(`Conversion took ${metrics.conversionTime}ms`);
Plugin System
Custom Renderers
You can extend the converter with custom renderers:
// Custom link renderer
const customRenderer = {
link(href, title, text) {
return `<a href="${href}" title="${title}" class="custom-link">${text}</a>`;
},
};
// Use custom renderer
const html = await convertMarkdown(markdown, {
renderer: customRenderer,
});
Custom Extensions
// Custom extension for handling special syntax
const customExtension = {
name: 'custom',
level: 'block',
start(src) {
return src.match(/:::/)?.index;
},
tokenizer(src, tokens) {
const match = src.match(/^:::\s*(\w+)\n([\s\S]*?)\n:::/);
if (match) {
return {
type: 'custom',
raw: match[0],
name: match[1],
content: match[2],
};
}
},
renderer(token) {
return `<div class="custom-block ${token.name}">${token.content}</div>`;
},
};
// Register extension
registerExtension(customExtension);
TypeScript Support
The API includes full TypeScript definitions:
import { convertMarkdown, ConversionOptions, HistoryRecord } from 'markdown-to-html';
const options: ConversionOptions = {
outputFormat: 'html',
sanitize: true,
gfm: true,
};
const html: string = await convertMarkdown('# Hello', options);
Browser Compatibility
Supported Browsers
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
Required Features
- ES2020 support
- Fetch API
- Clipboard API (optional)
- File API (optional)
Next Steps
Explore more:
- Examples for practical usage
- FAQ for common questions
- Related Tools for complementary tools