For a small formatting feature, start with a constrained contenteditable='true' surface, observe the browser’s input and selection events, and convert the resulting DOM into your own normalized document before saving. Use plaintext-only when formatting is unnecessary. For tables, mentions, collaboration, comments, or a large plugin set, evaluate a maintained editor framework. Choose EditContext only when you need custom rendering and precise control of IME composition and selection. Do not make new architecture depend on deprecated document.execCommand().
Choose the editing model before writing UI code
An HTML editor has two separate jobs: accepting text input and representing a document. The browser can provide the first job, but its DOM is not a stable document model. Decide what your application will store before choosing controls.
| Approach | Use it when | Costs and risks |
|---|---|---|
contenteditable with custom handlers |
A small, well-defined set of paragraphs, marks, links, or lists is enough. | You must own browser-markup normalization, paste handling, selection edge cases, undo behavior, and accessibility. |
| Maintained editor framework or component | You need tables, mentions, comments, collaboration, rich history, or many plugins. | Evaluate dependency size, schema migrations, licensing, and integration work. |
| EditContext with a custom renderer | You need custom drawing or layout plus advanced IME, emoji, or platform text-input behavior. | Your application owns document state, rendering, selection mapping, selection bounds, keyboard behavior, and edit handling. |
contenteditable is an editing primitive, not a complete document model. Keep the editable surface deliberately narrow: define the blocks and inline marks you support, then reject everything else.
Define a document contract
Write down the allowed structure before implementing toolbar buttons. A simple contract might allow paragraphs, headings, unordered lists, links, and bold or italic marks. Store either this normalized representation or sanitized HTML; never treat arbitrary browser-generated DOM as trusted data.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
{
'version': 1,
'blocks': [
{ 'type': 'paragraph', 'children': [
{ 'text': 'Release notes', 'marks': ['bold'] }
]},
{ 'type': 'paragraph', 'children': [
{ 'text': 'Read the ', 'marks': [] },
{ 'text': 'documentation', 'marks': [], 'href': 'https://example.com/docs' }
]}
]
}
Version the format. A future migration can then transform version 1 documents instead of guessing what an old HTML fragment meant. Validate the same contract on the server and render it with the same allowlist.
Build a constrained contenteditable surface
The following example supports paragraphs, plain-text paste, bold and italic marks, and a normalized HTML snapshot. It intentionally avoids execCommand. The mark function is suitable for a small demo where the selection is inside one text node; a production editor should apply marks through its document model so selections spanning several nodes behave consistently.
<label for='editor'>Article body</label>
<div class='toolbar' role='toolbar' aria-label='Formatting'>
<button type='button' data-mark='bold' aria-label='Bold'>Bold</button>
<button type='button' data-mark='italic' aria-label='Italic'>Italic</button>
</div>
<div id='editor' contenteditable='true' role='textbox' aria-multiline='true'
aria-labelledby='editor' spellcheck='true'><p><br></p></div>
<output id='status' aria-live='polite'></output>
<script>
const editor = document.querySelector('#editor');
const status = document.querySelector('#status');
let composing = false;
function allowedUrl(value) {
try {
const url = new URL(value, window.location.href);
return ['http:', 'https:'].includes(url.protocol) ? url.href : null;
} catch {
return null;
}
}
function normalize(root) {
// Convert browser-specific line breaks into paragraphs and remove
// elements and attributes outside the application contract.
root.querySelectorAll('script,style,iframe,object,embed,form').forEach(node => node.remove());
root.querySelectorAll('*').forEach(node => {
[...node.attributes].forEach(attribute => {
if (!['href','title'].includes(attribute.name)) node.removeAttribute(attribute.name);
});
if (node.matches('a')) {
const safe = allowedUrl(node.getAttribute('href') || '');
if (safe) node.setAttribute('href', safe);
else node.replaceWith(...node.childNodes);
}
});
root.querySelectorAll('div').forEach(div => {
const paragraph = document.createElement('p');
paragraph.innerHTML = div.innerHTML;
div.replaceWith(paragraph);
});
return root.innerHTML;
}
function saveDraft() {
const copy = editor.cloneNode(true);
const html = normalize(copy);
// Send html to your server, where the same allowlist is enforced.
status.textContent = 'Draft changed';
return html;
}
editor.addEventListener('beforeinput', event => {
// Use this event for model operations such as inserting paragraphs,
// deleting ranges, or applying marks. Do not cancel ordinary text input
// unless your model is ready to perform the replacement.
if (event.inputType === 'formatBold' || event.inputType === 'formatItalic') {
event.preventDefault();
}
});
editor.addEventListener('compositionstart', () => { composing = true; });
editor.addEventListener('compositionend', () => { composing = false; saveDraft(); });
editor.addEventListener('input', () => { if (!composing) saveDraft(); });
editor.addEventListener('paste', event => {
event.preventDefault();
const text = event.clipboardData.getData('text/plain');
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
range.deleteContents();
const fragment = document.createDocumentFragment();
text.split(/r?n/).forEach((line, index, lines) => {
fragment.append(document.createTextNode(line));
if (index < lines.length - 1) fragment.append(document.createElement('br'));
});
range.insertNode(fragment);
selection.collapseToEnd();
saveDraft();
});
document.querySelectorAll('[data-mark]').forEach(button => {
button.addEventListener('mousedown', event => event.preventDefault());
button.addEventListener('click', () => {
const selection = window.getSelection();
if (!selection.rangeCount || selection.isCollapsed) return;
const range = selection.getRangeAt(0);
if (!editor.contains(range.commonAncestorContainer)) return;
const tag = button.dataset.mark === 'bold' ? 'strong' : 'em';
const wrapper = document.createElement(tag);
try {
range.surroundContents(wrapper);
selection.removeAllRanges();
const next = document.createRange();
next.selectNodeContents(wrapper);
selection.addRange(next);
saveDraft();
} catch {
status.textContent = 'Select text within one paragraph to format it';
}
});
});
</script>
Give the surface a visible focus style and keep the label visible. The role='textbox' and aria-multiline='true' communicate its purpose to assistive technology; test with the screen readers and keyboard layouts your users rely on.
Handle input, selection, IME, and undo
Observe the right events
Use beforeinput when you need to translate an edit into a document operation, and input to observe the resulting change. Track selectionchange to keep toolbar state, link dialogs, and formatting indicators synchronized with the current selection. Do not assume that a keydown event describes the edit; virtual keyboards and assistive technology often do not produce the same key sequence.
Protect composition text
IME input is provisional: Japanese, Chinese, Korean, and other input methods compose text through multiple updates. Treat compositionstart through compositionend as one transaction. Avoid normalizing or rerendering the active text node during composition, or the caret can jump and the candidate window can break. Commit the final text after compositionend.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Preserve undo semantics
Users expect one undo step to reverse one logical action. If you replace the DOM after every keystroke, you can destroy the browser’s native history. Keep the editing surface stable, group programmatic changes deliberately, and maintain a model-level history when your application performs its own transformations. Test undo and redo after typing, paste, formatting, link insertion, and an IME commit.
Map selections safely
A DOM range can point into text nodes that your normalizer later merges or replaces. Before rerendering, capture a model position or a stable marker, then restore the selection after the update. Never trust a selection supplied by the client when applying a server-side operation.
Implement paste and clipboard behavior deliberately
Paste from word processors and web pages can contain nested spans, inline styles, tracking links, images, and event-handler attributes. Prefer plain text for a note field. For rich paste, parse the HTML, keep only your allowlisted tags and attributes, normalize lists and line breaks, and resolve links through a protocol allowlist. The Clipboard API is the preferred modern interface for clipboard operations; do not build new copy and paste flows around execCommand('copy').
Free tools Windows power users keep installed
One-click scans. No signup required.
Decide what happens to images before enabling them. You can remove them, convert them to approved uploads, or store references to an object-storage service. Never accept a pasted data URL or remote image URL without applying size, type, origin, and malware controls.
Normalize and sanitize at the trust boundary
Browser markup differs across engines. Enter may create a block element in one browser and a line break in another, and equivalent selections can produce different nesting. Normalize after input and again before persistence. A safe pipeline is:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
- Parse the fragment in an inert document.
- Drop disallowed elements, attributes, CSS, and event-handler content.
- Convert equivalent structures to your canonical blocks and marks.
- Validate URLs, uploaded files, and document size.
- Store the versioned result and render it with the same allowlist.
Client-side cleaning improves the editing experience but is not a security boundary. A user can bypass your JavaScript and submit an HTTP request directly, so server-side validation is mandatory. Escape text when rendering into a non-editor context, and use a well-maintained sanitizer rather than a regular-expression filter.
When EditContext is the better foundation
EditContext is intended for custom rich-text editors that need advanced text-input experiences such as IME composition, emoji pickers, or other platform-specific editing UI. With it, your application owns text state, rendering, selection mapping, selection bounds, and edit handling. That control is useful for a canvas-like renderer, a virtualized document, or a layout that cannot be represented by ordinary editable DOM.
Recommended Free Tools
The trade-off is substantial: you must implement caret painting, hit testing, keyboard navigation, deletion rules, bidirectional text behavior, accessibility exposure, and model synchronization. Treat EditContext as an explicit investment, not a drop-in replacement for contenteditable, and verify availability in every browser and WebView you support before committing to it.
Accessibility and mobile requirements
- Provide a persistent accessible name and a visible focus indicator.
- Keep toolbar controls reachable by keyboard and expose pressed state for toggles.
- Do not use placeholder text as the only label.
- Test arrow-key navigation, Home and End, selection extension, and deletion with a screen reader running.
- Check mobile keyboards, rotation, zoom, autocorrect, spellcheck, and long-press selection.
- Ensure dialogs for links or embeds return focus to the editor and preserve the selection.
Testing checklist before shipping
- Type, delete, select across marks, and undo or redo every command.
- Compose text with at least one IME and insert emoji.
- Paste plain text, rich web content, and a document copied from a word processor.
- Press Enter at the start, middle, and end of paragraphs in every supported browser.
- Paste malformed HTML, dangerous URLs, SVG, data URLs, and oversized content.
- Navigate the complete editor with keyboard-only and screen-reader controls.
- Open an old document after a schema migration and verify that it renders identically.
- Throttle the network, interrupt autosave, reload during a save, and recover without losing the latest acknowledged draft.
Troubleshoot common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Enter creates inconsistent spacing or tags | Browser-specific block and break behavior is being saved directly. | Convert blocks to your canonical paragraph model before persistence. |
| Caret jumps while typing an accented or East Asian language | The DOM is being rerendered during composition. | Defer normalization until compositionend and restore a model selection. |
| Undo removes several unrelated edits | Programmatic DOM replacement collapsed the browser history. | Keep nodes stable, group intentional transactions, or use model-level history. |
| Pasted content contains scripts or tracking links | Raw clipboard HTML was inserted or only cleaned in the browser. | Parse through an allowlist and repeat validation on the server. |
| Formatting fails for a multi-node selection | Range.surroundContents() cannot wrap partially selected elements. |
Apply a mark operation to model ranges, splitting text nodes as needed. |
| Toolbar clicks lose the selection | Focus moved before the command read the range. | Record the selection, prevent toolbar mousedown from stealing focus, then restore it. |
| Saved HTML renders differently from the editor | Rendering and editing use different sanitizers or schemas. | Share one versioned contract and allowlist at both boundaries. |
Performance, reliability, and operating cost
Keep the live DOM limited to the visible editing surface; very large documents may need pagination or virtualization, which is easier with a model-driven framework. Debounce autosave, but show whether a change is unsaved and retain the last acknowledged revision. Send small operations or compressed document snapshots rather than repeatedly uploading identical HTML. Add request identifiers so a delayed response cannot overwrite a newer draft.
Measure the behaviors that affect users—input latency, composition stability, paste time, document size, and recovery after a failed save—on the devices and browsers you support. There is no single browser-support percentage or performance number that substitutes for those tests.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Or skip the browser setup
If your immediate need is obtaining clean screenshots of the editor, documentation, or rendered HTML rather than building a capture pipeline, ScreenshotNeo provides a single website-screenshot API call. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
curl -G 'https://api.screenshotneo.com/v1/shot' -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for the options and response details. You can also call it from Python:
import requests
r = requests.get('https://api.screenshotneo.com/v1/shot', params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'}, timeout=90)
open('shot.webp', 'wb').write(r.content)
Or from Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Should every editor store HTML?
No. A versioned document model is easier to validate, migrate, and render consistently. Store sanitized HTML only when its structure is your deliberate contract.
Can I keep using execCommand in an old editor?
It may maintain legacy behavior, but the API is deprecated. Avoid adding new architecture around it and plan a migration toward input events, model operations, and the Clipboard API.
When is plaintext-only the right choice?
Use contenteditable='plaintext-only' for notes, titles, or other fields where raw text is required and rich formatting would add risk without value.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Do I need a framework for a two-button editor?
Not necessarily. A constrained surface can be appropriate when your team is prepared to own normalization, paste, selection, undo, accessibility, and server-side sanitization. Reconsider when those requirements expand.
Frequently Asked Questions
How do I prevent an editor from saving unsafe markup?
Define an allowlist, normalize pasted and browser-generated DOM into it, and validate again on the server before storing or rendering.
Why does IME support require special handling?
IME text is composed through provisional updates; rerendering during composition can move the caret or disrupt the candidate window, so commit after compositionend.
What is the main reason to choose EditContext?
It gives a custom renderer control over text state, selection, bounds, and input behavior when contenteditable cannot provide the required layout or IME experience.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

