The headless browser for AI agents and web scraping
fix(js): handle setRangeText defaults and input type fallback
SGavrl7451e39ea651
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 016f658b..0139cee1 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -3501,6 +3501,13 @@ function _setElemHrefPart(el, part, value) {if (c) el.setAttribute('href', c.href);}+// Unknown input types use the text state and support selection.+const _INPUT_NO_SELECTION_TYPES = new Set([+ 'hidden', 'email', 'date', 'month', 'week', 'time', 'datetime-local',+ 'number', 'range', 'color', 'checkbox', 'radio', 'file',+ 'submit', 'image', 'reset', 'button',+]);+// --- <input> number/date conversion (valueAsNumber/valueAsDate/stepUp/Down) ---// Applicable types and their step scale factor + default step (HTML spec).const _INPUT_NUM_TYPES = { date: 1, month: 1, week: 1, time: 1, 'datetime-local': 1, number: 1, range: 1 };@@ -5045,6 +5052,13 @@ class Element extends Node {if (tag === 'textarea') {this.textContent = value;}+ // Programmatic value assignment places the text cursor at the end in+ // Chromium. setRangeText() uses that position when preserving selection.+ const type = tag === 'input' ? (this.getAttribute('type') || 'text').toLowerCase() : '';+ if (tag === 'textarea' ||+ (tag === 'input' && !_INPUT_NO_SELECTION_TYPES.has(type))) {+ this.setSelectionRange(value.length, value.length);+ }}get min() { return this.getAttribute('min') || ''; }set min(v) { this.setAttribute('min', v); }@@ -19341,32 +19355,51 @@ if (!Element.prototype.setSelectionRange) {_markNative(Element.prototype.setSelectionRange);}-// Element.prototype.setRangeText - replace selection with text+// Element.prototype.setRangeText - replace selected text, preserving the+// selection around edits as HTMLInputElement/HTMLTextAreaElement do.if (!Element.prototype.setRangeText) {Element.prototype.setRangeText = function setRangeText(replacement, start, end, selectMode) {- const val = this.value;- if (!val) return;- const strVal = String(val);- start = start === undefined ? (this.selectionStart ?? 0) : Math.max(0, parseInt(start, 10) || 0);- end = end === undefined ? (this.selectionEnd ?? 0) : Math.max(0, parseInt(end, 10) || 0);- const newValue = strVal.slice(0, start) + String(replacement) + strVal.slice(end);- this.value = newValue;- selectMode = selectMode || 'preserve';- if (selectMode === 'select') {- const replLen = String(replacement).length;- _ns_selectionStart.set(this, start);- _ns_selectionEnd.set(this, start + replLen);- _ns_selectionDir.set(this, 'none');- } else if (selectMode === 'start') {- _ns_selectionStart.set(this, start);- _ns_selectionEnd.set(this, start);- _ns_selectionDir.set(this, 'none');- } else if (selectMode === 'end') {- const replLen = String(replacement).length;- _ns_selectionStart.set(this, start + replLen);- _ns_selectionEnd.set(this, start + replLen);- _ns_selectionDir.set(this, 'none');- }+ const tag = this.localName;+ const inputType = tag === 'input' ? (this.getAttribute('type') || 'text').toLowerCase() : '';+ if (tag !== 'textarea' && !(tag === 'input' &&+ !_INPUT_NO_SELECTION_TYPES.has(inputType))) {+ throw new DOMException('This input element does not support text selection.', 'InvalidStateError');+ }+ if (arguments.length < 1 || arguments.length === 2)+ throw new TypeError("Failed to execute 'setRangeText': invalid number of arguments");+ const mode = selectMode === undefined ? 'preserve' : String(selectMode);+ if (!['select', 'start', 'end', 'preserve'].includes(mode))+ throw new TypeError("Failed to execute 'setRangeText': invalid selection mode");+ const value = String(this.value ?? '');+ const text = String(replacement);+ let lo = arguments.length < 3 ? (this.selectionStart ?? 0) : Math.max(0, Math.trunc(Number(start)) || 0);+ let hi = arguments.length < 3 ? (this.selectionEnd ?? 0) : Math.max(0, Math.trunc(Number(end)) || 0);+ if (lo > hi) throw new DOMException('Start is greater than end.', 'IndexSizeError');+ lo = Math.min(lo, value.length);+ hi = Math.min(hi, value.length);+ const beforeStart = Math.min(this.selectionStart ?? 0, value.length);+ const beforeEnd = Math.min(this.selectionEnd ?? 0, value.length);+ this.value = value.slice(0, lo) + text + value.slice(hi);+ const afterEnd = lo + text.length;+ const delta = text.length - (hi - lo);+ let selectionStart = beforeStart;+ let selectionEnd = beforeEnd;+ if (mode === 'select') {+ selectionStart = lo;+ selectionEnd = afterEnd;+ } else if (mode === 'start') {+ selectionStart = selectionEnd = lo;+ } else if (mode === 'end') {+ selectionStart = selectionEnd = afterEnd;+ } else {+ // Preserve offsets before the replaced range, shift offsets after it,+ // and collapse selection endpoints that intersect the replaced text.+ if (selectionStart > hi) selectionStart += delta;+ else if (selectionStart > lo) selectionStart = lo;+ if (selectionEnd > hi) selectionEnd += delta;+ else if (selectionEnd > lo) selectionEnd = afterEnd;+ }+ this.setSelectionRange(selectionStart, selectionEnd, 'forward');};_markNative(Element.prototype.setRangeText);}diff --git a/crates/obscura-js/tests/range_text_compat.rs b/crates/obscura-js/tests/range_text_compat.rsnew file mode 100644index 00000000..674bf4f3--- /dev/null+++ b/crates/obscura-js/tests/range_text_compat.rs@@ -0,0 +1,91 @@+use obscura_js::runtime::ObscuraJsRuntime;+use serde_json::json;++#[test]+fn set_range_text_matches_chromium_for_empty_and_nonempty_controls() {+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(obscura_dom::parse_html(+ r#"<textarea id="t"></textarea><input id="i"><input id="n" type="number">"#,+ ));+ rt.run_page_init();+ let value = rt.evaluate(r#"(() => {+ const t = document.getElementById('t');+ const out = {};+ const run = (name, initial, selection, replacement, args) => {+ t.value = initial;+ t.setSelectionRange(...selection);+ try {+ t.setRangeText(replacement, ...args);+ out[name] = [t.value, t.selectionStart, t.selectionEnd, t.selectionDirection];+ } catch (e) { out[name] = e.name; }+ };+ run('empty', '', [0, 0], 'a', []);+ run('before', 'abcdef', [0, 0], 'XYZ', [1, 3]);+ run('overlap', 'abcdef', [1, 2], 'XYZ', [1, 3]);+ run('after', 'abcdef', [3, 5], 'XYZ', [1, 3]);+ run('preserve', 'abcdef', [1, 5], 'XYZ', [2, 4, 'preserve']);+ run('undefinedMode', 'abcdef', [1, 5], 'XYZ', [2, 4, undefined]);+ run('select', 'abcdef', [0, 0], 'X', [1, 3, 'select']);+ run('start', 'abcdef', [0, 0], 'X', [1, 3, 'start']);+ run('end', 'abcdef', [0, 0], 'X', [1, 3, 'end']);+ run('invalid', 'abcdef', [0, 0], 'X', [1, 3, 'invalid']);+ run('nullMode', 'abcdef', [0, 0], 'X', [1, 3, null]);+ run('reversed', 'abcdef', [0, 0], 'X', [5, 1]);+ run('beyond', 'abc', [0, 0], 'X', [6, 9]);+ const i = document.getElementById('i');+ i.value = 'abc';+ out.inputAssignment = [i.selectionStart, i.selectionEnd];+ i.setRangeText('X', 1, 2);+ out.input = [i.value, i.selectionStart, i.selectionEnd];+ i.setRangeText('Y', 0, 1, undefined);+ out.inputUndefinedMode = [i.value, i.selectionStart, i.selectionEnd];+ out.fallbackInputs = [+ 'future-state', ' text ', 'constructor', '__proto__', 'datetime', 'TeXt',+ 'search', 'tel', 'url', 'password', '',+ ].map(type => {+ const input = document.createElement('input');+ input.setAttribute('type', type);+ input.value = 'abc';+ const assigned = [input.selectionStart, input.selectionEnd];+ try {+ input.setRangeText('X', 0, 1);+ return [...assigned, input.value, input.selectionStart, input.selectionEnd];+ } catch (e) { return e.name; }+ });+ out.unsupportedInputs = [+ 'hidden', 'email', 'date', 'month', 'week', 'time', 'datetime-local',+ 'NuMbEr', 'range', 'color', 'checkbox', 'radio', 'file',+ 'submit', 'image', 'reset', 'button',+ ].map(type => {+ const input = document.createElement('input');+ input.setAttribute('type', type);+ try { input.setRangeText('X', 0, 0); }+ catch (e) { return e.name; }+ return 'no exception';+ });+ try { document.getElementById('n').setRangeText('X', 1, 2); }+ catch (e) { out.number = e.name; }+ return out;+ })()"#).unwrap();+ assert_eq!(value, json!({+ "empty": ["a", 0, 0, "forward"],+ "before": ["aXYZdef", 0, 0, "forward"],+ "overlap": ["aXYZdef", 1, 4, "forward"],+ "after": ["aXYZdef", 1, 6, "forward"],+ "preserve": ["abXYZef", 1, 6, "forward"],+ "undefinedMode": ["abXYZef", 1, 6, "forward"],+ "select": ["aXdef", 1, 2, "forward"],+ "start": ["aXdef", 1, 1, "forward"],+ "end": ["aXdef", 2, 2, "forward"],+ "invalid": "TypeError",+ "nullMode": "TypeError",+ "reversed": "IndexSizeError",+ "beyond": ["abcX", 0, 0, "forward"],+ "input": ["aXc", 3, 3],+ "inputUndefinedMode": ["YXc", 3, 3],+ "inputAssignment": [3, 3],+ "fallbackInputs": vec![json!([3, 3, "Xbc", 3, 3]); 11],+ "unsupportedInputs": vec!["InvalidStateError"; 17],+ "number": "InvalidStateError"+ }));+}