Selection mismatch between beforeinput and input events
OS: Android 10-14 · Device: Mobile (Samsung Galaxy series) Any · Browser: Chrome for Android 120+ · Keyboard: Korean (IME) - Samsung Keyboard with Text Prediction ON
Open case →Scenario
The selection (window.getSelection()) in beforeinput events can differ from the selection in corresponding input events. This mismatch can occur during IME composition, text prediction, or when typing adjacent to formatted elements like links. The selection in beforeinput may include adjacent formatted text, while input selection reflects the final cursor position.
The selection (window.getSelection()) in beforeinput events can differ from the selection in corresponding input events. This mismatch can occur during IME composition, text prediction, or when typing adjacent to formatted elements like links. The selection in beforeinput may include adjacent formatted text, while input selection reflects the final cursor position.
When handling input events in contenteditable elements, developers often assume that the selection in beforeinput matches the selection in input. However, this is not always the case:
beforeinput: May include adjacent formatted elements (links, bold, italic, etc.)input: Reflects the final cursor position after DOM changesWhen typing text next to an anchor link:
// HTML: <a href="...">Link text</a> [cursor here]
element.addEventListener('beforeinput', (e) => {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// beforeinput selection may include the link
// range.startContainer might be the <a> element
// range.startOffset and range.endOffset may include link text
});
element.addEventListener('input', (e) => {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// input selection reflects final cursor position
// range.startContainer is likely a text node after the link
// range.startOffset is the position in that text node
});
During IME composition, selections can differ:
element.addEventListener('beforeinput', (e) => {
if (e.inputType === 'insertCompositionText') {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// beforeinput selection shows where composition will be inserted
// May include existing composition text
}
});
element.addEventListener('input', (e) => {
if (e.inputType === 'insertCompositionText') {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// input selection shows final cursor position after composition
// Different from beforeinput selection
}
});
With text prediction enabled, selections can be particularly inconsistent:
element.addEventListener('beforeinput', (e) => {
if (e.inputType === 'insertCompositionText') {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// Selection may include adjacent link text
// range.startContainer might be link element
// range includes more than just the insertion point
}
});
element.addEventListener('input', (e) => {
if (e.inputType === 'insertCompositionText') {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
// Selection reflects actual cursor position
// Different container and offset from beforeinput
}
});
beforeinput selection may track wrong positionsbeforeinput selection may not match DOM statelet beforeInputSelection = null;
element.addEventListener('beforeinput', (e) => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
beforeInputSelection = selection.getRangeAt(0).cloneRange();
}
});
element.addEventListener('input', (e) => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const inputSelection = selection.getRangeAt(0).cloneRange();
// Compare selections
if (beforeInputSelection && !selectionsMatch(beforeInputSelection, inputSelection)) {
console.warn('Selection mismatch detected');
// Handle mismatch
handleSelectionMismatch(beforeInputSelection, inputSelection);
}
}
beforeInputSelection = null;
});
function selectionsMatch(range1, range2) {
if (!range1 || !range2) return false;
return range1.startContainer === range2.startContainer &&
range1.startOffset === range2.startOffset &&
range1.endContainer === range2.endContainer &&
range1.endOffset === range2.endOffset;
}
Normalize selections to exclude formatted elements:
function normalizeSelection(range) {
if (!range) return null;
let container = range.startContainer;
if (container.nodeType === Node.TEXT_NODE) {
container = container.parentElement;
}
// Check if selection is inside a formatted element
const link = container.closest('a');
const bold = container.closest('b, strong');
const italic = container.closest('i, em');
// If selection is at the boundary of a formatted element, adjust
if (link && range.startContainer === link) {
// Adjust to position after link
const normalized = document.createRange();
try {
normalized.setStartAfter(link);
normalized.collapse(true);
return normalized;
} catch (e) {
return range;
}
}
// If selection is inside formatted element but at end, adjust
if ((link || bold || italic) && range.collapsed) {
const element = link || bold || italic;
if (range.startOffset === element.textContent.length) {
// At end of formatted element, move to after
const normalized = document.createRange();
try {
normalized.setStartAfter(element);
normalized.collapse(true);
return normalized;
} catch (e) {
return range;
}
}
}
return range.cloneRange();
}
element.addEventListener('beforeinput', (e) => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const normalized = normalizeSelection(range);
// Use normalized range for processing
}
});
Prefer getTargetRanges() from beforeinput over window.getSelection():
element.addEventListener('beforeinput', (e) => {
const targetRanges = e.getTargetRanges?.() || [];
if (targetRanges.length > 0) {
// Use targetRanges - they're more accurate
const range = targetRanges[0];
// Process with targetRanges
} else {
// Fallback to window.getSelection() but normalize
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = normalizeSelection(selection.getRangeAt(0));
// Process with normalized range
}
}
});
When selections don’t match, compare DOM state to understand actual changes:
let domState = null;
element.addEventListener('beforeinput', (e) => {
const selection = window.getSelection();
const range = selection && selection.rangeCount > 0
? selection.getRangeAt(0).cloneRange()
: null;
domState = {
html: element.innerHTML,
text: element.textContent,
selection: range,
selectionNormalized: normalizeSelection(range)
};
});
element.addEventListener('input', (e) => {
const selection = window.getSelection();
const range = selection && selection.rangeCount > 0
? selection.getRangeAt(0).cloneRange()
: null;
const inputState = {
html: element.innerHTML,
text: element.textContent,
selection: range,
selectionNormalized: normalizeSelection(range)
};
// Compare selections
if (domState && !selectionsMatch(
domState.selectionNormalized,
inputState.selectionNormalized
)) {
// Selections don't match - use DOM comparison
const actualChange = compareDOM(domState, inputState);
handleActualChange(actualChange);
}
domState = null;
});
Special handling for typing next to links:
function isAdjacentToLink(range) {
let container = range.startContainer;
if (container.nodeType === Node.TEXT_NODE) {
container = container.parentElement;
}
const link = container.closest('a');
if (!link) return false;
// Check if cursor is at boundary of link
if (range.collapsed) {
if (range.startContainer === link) {
return true; // Cursor is inside link element
}
// Check if cursor is immediately after link
const textNode = range.startContainer;
if (textNode.nodeType === Node.TEXT_NODE) {
const parent = textNode.parentElement;
const linkSibling = link.nextSibling;
if (linkSibling === parent || linkSibling === textNode) {
return true;
}
}
}
return false;
}
element.addEventListener('beforeinput', (e) => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
if (isAdjacentToLink(range)) {
// Special handling for link-adjacent input
const normalized = normalizeSelectionForLink(range);
handleLinkAdjacentInput(normalized, e);
}
}
});
function normalizeSelectionForLink(range) {
let container = range.startContainer;
if (container.nodeType === Node.TEXT_NODE) {
container = container.parentElement;
}
const link = container.closest('a');
if (link) {
// Move selection to after link
const normalized = document.createRange();
try {
// Find text node after link
let afterLink = link.nextSibling;
while (afterLink && afterLink.nodeType !== Node.TEXT_NODE) {
afterLink = afterLink.nextSibling;
}
if (afterLink) {
normalized.setStart(afterLink, 0);
} else {
// Create text node after link
const textNode = document.createTextNode('');
link.parentNode.insertBefore(textNode, link.nextSibling);
normalized.setStart(textNode, 0);
}
normalized.collapse(true);
return normalized;
} catch (e) {
return range;
}
}
return range.cloneRange();
}
beforeinput and input selectionsgetTargetRanges(): Use getTargetRanges() from beforeinput when availablebeforeinput for use in input handlerce-0295: insertCompositionText event and selection mismatch when typing next to a link with Samsung keyboard text prediction ONVisual view of how this scenario connects to its concrete cases and environments. Nodes can be dragged and clicked.
Each row is a concrete case for this scenario, with a dedicated document and playground.
| Case | OS | Device | Browser | Keyboard | Status |
|---|---|---|---|---|---|
| ce-0547-beforeinput-input-selection-mismatch-en | Android 10-14 | Mobile (Samsung Galaxy series) Any | Chrome for Android 120+ | Korean (IME) - Samsung Keyboard with Text Prediction ON | draft |
Open a case to see the detailed description and its dedicated playground.
OS: Android 10-14 · Device: Mobile (Samsung Galaxy series) Any · Browser: Chrome for Android 120+ · Keyboard: Korean (IME) - Samsung Keyboard with Text Prediction ON
Open case →Other scenarios that share similar tags or category.
The getTargetRanges() method in beforeinput events may return an empty array or undefined in various scenarios, including text prediction, certain IME compositions, or specific browser/device combinations. When getTargetRanges() is unavailable, developers must rely on window.getSelection() as a fallback, but this may be less accurate.
During IME composition or in certain browser/IME combinations, the beforeinput event may have a different inputType than the corresponding input event. For example, beforeinput may fire with insertCompositionText while input fires with deleteContentBackward. This mismatch can cause handlers to misinterpret the actual DOM change and requires storing beforeinput's targetRanges for use in input event handling.
In Safari desktop, when preventDefault() is called on keydown or beforeinput events for insertParagraph (Enter key), the IME composition state becomes corrupted. Subsequent text input fails to trigger proper input events, causing characters to not be inserted or composition to malfunction.
On iOS, when using voice dictation to input text into contenteditable elements, the system may fire duplicate beforeinput and input events after the initial dictation completes. The text is split into words and events are re-fired, causing synchronization issues. Composition events do not fire during dictation, making it difficult to distinguish dictation from keyboard input.
Analysis of how out-of-order or missing composition events disrupt editor state synchronization.
Have questions, suggestions, or want to share your experience? Join the discussion below.