The HTML Block API provides a comprehensive set of tools and methods for creating interactive components within Karbonized. This API is available through the global htmlBlockAPI object and includes DOM manipulation utilities, logging, refresh capabilities, action registration, and advanced file handling. The HTML Block runs in a Shadow DOM environment for secure encapsulation.
The HTML Block API is automatically injected into the global scope and can be accessed in multiple ways:
// Direct access
htmlBlockAPI.log('Hello World');
// Via window object
window.htmlBlockAPI.log('Hello World');
// Safe access with fallback
const api = window.htmlBlockAPI || {};
api.log?.('Hello World');Logs messages to the parent application console with HTML Block context.
Parameters:
message(unknown): The message to log. Can be string, number, object, or any serializable data.
Returns: void
Example:
htmlBlockAPI.log('Debug message');
htmlBlockAPI.log({ user: 'John', action: 'click' });Requests a refresh of the HTML Block content from the parent application.
Returns: void
Example:
htmlBlockAPI.refresh();Logs warning messages to the console with HTML Block context.
Parameters:
message(unknown): The warning message to log.
Returns: void
Example:
htmlBlockAPI.warn('Deprecated method used');Logs error messages to the console with HTML Block context.
Parameters:
message(unknown): The error message to log.
Returns: void
Example:
htmlBlockAPI.error('Something went wrong');Registers a custom action handler that can be triggered from the UI.
Parameters:
actionId(string): Unique identifier for the actionhandler(function): Function to execute when action is triggered
Returns: void
Example:
htmlBlockAPI.registerAction('myAction', () => {
console.log('Action executed');
});Karbonized can generate action buttons from JavaScript comments using the // @action:... syntax.
// @action:Say Hello
log('Hello from the action');If the action block contains a function declaration or a function assigned to a variable, Karbonized will register the action and invoke that function automatically when the action button is pressed.
// @action:Add Images
async function addImages() {
const files = await htmlBlockAPI.uploadFile({
accept: ['image/*'],
multiple: true,
});
log(`Imported ${Array.isArray(files) ? files.length : 1} images`);
}// @action:Refresh Layout
const refreshLayout = () => {
htmlBlockAPI.refresh();
};Custom actions only run when Allow Script Execution is enabled for the HTML Block.
Uploads files with validation and converts images to data URLs.
Parameters:
options(FileUploadOptions, optional): Configuration optionsaccept(string[]): Accepted file types (e.g., ['image/*', '.pdf'])multiple(boolean): Allow multiple file selectionmaxSize(number): Maximum file size in bytesmaxFiles(number): Maximum number of filesconvertToDataUrl(boolean): Convert images to data URLs
Returns: Promise<FileInfo | FileInfo[]>
Notes:
- The file picker is mounted temporarily in the DOM before opening, which improves compatibility with Electron and embedded webviews.
- The promise rejects when the user cancels selection, when the selection exceeds
maxFiles, or when no selected file passes validation.
Example:
// Upload multiple images
const images = await htmlBlockAPI.uploadFile({
accept: ['image/*'],
multiple: true,
maxSize: 5 * 1024 * 1024, // 5MB
convertToDataUrl: true,
});
// Upload single PDF
const pdf = await htmlBlockAPI.uploadFile({
accept: ['application/pdf'],
maxSize: 10 * 1024 * 1024, // 10MB
});Common error handling:
try {
const uploaded = await htmlBlockAPI.uploadFile({
accept: ['image/*'],
multiple: true,
maxFiles: 4,
});
} catch (error) {
htmlBlockAPI.warn(`Upload cancelled or rejected: ${error.message}`);
}Retrieves file information by ID.
Parameters:
fileId(string): Unique file identifier
Returns: FileInfo | null
Example:
const file = htmlBlockAPI.getFile('file_123456');
if (file) {
console.log('File name:', file.name);
console.log('File size:', file.size);
console.log('Data URL:', file.dataUrl);
}Returns all uploaded files.
Returns: FileInfo[]
Example:
const allFiles = htmlBlockAPI.getAllFiles();
console.log('Total files:', allFiles.length);Removes a file by ID and cleans up resources.
Parameters:
fileId(string): Unique file identifier
Returns: void
Example:
htmlBlockAPI.removeFile('file_123456');Removes all files and cleans up resources.
Returns: void
Example:
htmlBlockAPI.clearFiles();Validates a file against specified options.
Parameters:
file(File): File object to validateoptions(FileUploadOptions, optional): Validation options
Returns: boolean
Example:
const isValid = htmlBlockAPI.validateFile(file, {
accept: ['image/*'],
maxSize: 5 * 1024 * 1024,
});Converts a file to a data URL.
Parameters:
file(File): File to convert
Returns: Promise<string>
Example:
const dataUrl = await htmlBlockAPI.convertToDataUrl(file);
const img = document.createElement('img');
img.src = dataUrl;Optimizes an image by resizing and compressing.
Parameters:
dataUrl(string): Image data URLoptions(ImageOptimizationOptions, optional): Optimization settingsmaxWidth(number): Maximum width in pixelsmaxHeight(number): Maximum height in pixelsquality(number): Quality 0-1 (for JPEG/WebP)format('jpeg' | 'png' | 'webp'): Output format
Returns: Promise<string>
Example:
const optimized = await htmlBlockAPI.optimizeImage(dataUrl, {
maxWidth: 1920,
maxHeight: 1080,
quality: 0.8,
format: 'jpeg',
});Reference to the HTML Block host element in the parent DOM.
Type: HTMLElement
Example:
const hostRect = htmlBlockAPI.host.getBoundingClientRect();
console.log('Host width:', hostRect.width);Reference to the root element inside the Shadow DOM.
Type: HTMLElement
Example:
htmlBlockAPI.root.style.padding = '20px';
htmlBlockAPI.root.classList.add('custom-class');Reference to the Shadow DOM root object.
Type: ShadowRoot
Example:
const button = htmlBlockAPI.shadowRoot.querySelector('button');
if (button) {
button.addEventListener('click', () => {
htmlBlockAPI.log('Button clicked');
});
}Reference to a scoped document object for safe DOM manipulation within the Shadow DOM.
Type: Document & ShadowRoot
Available Methods:
querySelector(selector: string): Element | nullquerySelectorAll(selector: string): NodeListOf<Element>getElementById(id: string): Element | nullcreateElement(tagName: string): ElementaddEventListener(type: string, listener: EventListener): voidremoveEventListener(type: string, listener: EventListener): voiddispatchEvent(event: Event): booleanactiveElement: Element | null
Example:
const element = htmlBlockAPI.document.querySelector('.my-class');
const newElement = htmlBlockAPI.document.createElement('div');Reference to the actual browser document object (parent window).
Type: Document
Example:
const parentStyles = htmlBlockAPI.globalDocument.getComputedStyle(
htmlBlockAPI.host,
);
const parentUrl = htmlBlockAPI.globalDocument.URL;Reference to the SafeDOM API for secure DOM manipulation within the Shadow DOM.
Type: SafeDOMAPI
The safeDOM object provides secure methods for DOM manipulation that prevent "Illegal invocation" errors.
Safely selects an element within the Shadow DOM.
Parameters:
selector(string): CSS selector string
Returns: Element | null
Safely selects multiple elements within the Shadow DOM.
Parameters:
selector(string): CSS selector string
Returns: NodeListOf<Element>
Safely creates a new DOM element.
Parameters:
tagName(string): Tag name for the element
Returns: Element | null
Safely appends a child element to a parent.
Parameters:
parent(Element): Parent elementchild(Element): Child element to append
Returns: boolean - Success status
Safely removes a child element from a parent.
Parameters:
parent(Element): Parent elementchild(Element): Child element to remove
Returns: boolean - Success status
Safely sets an attribute on an element.
Parameters:
element(Element): Target elementname(string): Attribute namevalue(string): Attribute value
Returns: boolean - Success status
Safely gets an attribute from an element.
Parameters:
element(Element): Target elementname(string): Attribute name
Returns: string | null - Attribute value
Safely sets a CSS style property on an element.
Parameters:
element(Element): Target elementproperty(string): CSS property namevalue(string): CSS property value
Returns: boolean - Success status
Safely gets a CSS style property from an element.
Parameters:
element(Element): Target elementproperty(string): CSS property name
Returns: string | null - CSS property value
Reference to the file utilities object with helper functions.
Type: FileUtils
Gets file extension from filename.
Parameters:
filename(string): File name
Returns: string
Example:
const ext = htmlBlockAPI.fileUtils.getExtension('photo.jpg'); // returns 'jpg'Formats file size in human readable format.
Parameters:
bytes(number): File size in bytes
Returns: string
Example:
const size = htmlBlockAPI.fileUtils.formatFileSize(1024); // returns '1 KB'Checks if file is an image.
Parameters:
file(File | FileInfo): File to check
Returns: boolean
Example:
const isImg = htmlBlockAPI.fileUtils.isImage(file);Checks if file is a video.
Parameters:
file(File | FileInfo): File to check
Returns: boolean
Checks if file is an audio file.
Parameters:
file(File | FileInfo): File to check
Returns: boolean
Gets MIME type from file extension.
Parameters:
extension(string): File extension
Returns: string
Example:
const mimeType = htmlBlockAPI.fileUtils.getMimeType('pdf'); // returns 'application/pdf'interface FileInfo {
id: string;
name: string;
type: string;
size: number;
url: string;
dataUrl?: string;
lastModified: number;
}interface FileUploadOptions {
accept?: string[];
multiple?: boolean;
maxSize?: number;
maxFiles?: number;
convertToDataUrl?: boolean;
}interface ImageOptimizationOptions {
maxWidth?: number;
maxHeight?: number;
quality?: number;
format?: 'jpeg' | 'png' | 'webp';
}HTML Blocks run in a Shadow DOM environment which provides:
- CSS scoping to prevent conflicts with parent page
- JavaScript encapsulation for safe execution
- DOM isolation from the main document
- Always use
htmlBlockAPI.safeDOMfor DOM manipulation - Use
htmlBlockAPI.documentfor element selection - Avoid direct access to
windowwhen possible
- Files are stored in memory and referenced by ID
- Data URLs are only generated for images under 5MB by default
- File type validation is performed but should not be supplemented with server-side validation
- Always sanitize file names when displaying them
- Use file size limits to prevent memory exhaustion
HTML Blocks follow standard browser security policies:
- External resource loading follows CORS policies
- Same-origin policies apply to network requests
- Standard browser permissions and restrictions
All SafeDOM methods include built-in error handling:
- Errors are logged to console with context
- Methods return
nullorfalseon failure - No exceptions are thrown to the calling code
A global safe wrapper for querySelector that handles errors gracefully.
Parameters:
selector(string): CSS selector string
Returns: Element | null
Example:
const element = safeQuerySelector('.my-selector');
if (element) {
element.textContent = 'Found safely!';
}