Skip to content

The headless browser for AI agents and web scraping

fix(js): preserve input selection and convert range offsets

SGavrl48538d635539
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 0139cee1..d614cac5 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -5047,17 +5047,32 @@ class Element extends Node {
return;
}
const value = String(v);
+ const type = tag === 'input' ? (this.getAttribute('type') || 'text').toLowerCase() : '';
+ const supportsSelection = tag === 'textarea' ||
+ (tag === 'input' && !_INPUT_NO_SELECTION_TYPES.has(type));
+ let changed = false;
+ if (supportsSelection) {
+ if (_formValues[this._nid] === undefined) _loadFormState(this._nid);
+ let previous = _formValues[this._nid];
+ if (previous === undefined) {
+ previous = (tag === 'textarea'
+ ? _domParse('text_content', this._nid)
+ : _domParse('get_attribute', this._nid, 'value')) ?? '';
+ }
+ changed = previous !== value;
+ }
_formValues[this._nid] = value;
_dom("set_form_value", this._nid, value);
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);
+ // Assigning the same value preserves selection. Internal updates must not
+ // invoke a page override of setSelectionRange().
+ if (changed || (supportsSelection && !_ns_selectionStart.has(this))) {
+ const position = changed ? value.length : 0;
+ _ns_selectionStart.set(this, position);
+ _ns_selectionEnd.set(this, position);
+ _ns_selectionDir.set(this, 'none');
}
}
get min() { return this.getAttribute('min') || ''; }
@@ -19372,8 +19387,8 @@ if (!Element.prototype.setRangeText) {
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);
+ let lo = arguments.length < 3 ? (this.selectionStart ?? 0) : (+start >>> 0);
+ let hi = arguments.length < 3 ? (this.selectionEnd ?? 0) : (+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);
diff --git a/crates/obscura-js/tests/range_text_compat.rs b/crates/obscura-js/tests/range_text_compat.rs
index 674bf4f3..f477e20e 100644
--- a/crates/obscura-js/tests/range_text_compat.rs
+++ b/crates/obscura-js/tests/range_text_compat.rs
@@ -1,6 +1,79 @@
use obscura_js::runtime::ObscuraJsRuntime;
use serde_json::json;
+#[test]
+fn value_assignment_preserves_unchanged_selection_without_calling_page_methods() {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(obscura_dom::parse_html("<input id='i' value='abc'><textarea id='t'>abc</textarea>"));
+ rt.run_page_init();
+ let value = rt.evaluate(r#"(() => {
+ return ['i', 't'].map(id => {
+ const element = document.getElementById(id);
+ element.value = 'abc';
+ const initial = [element.selectionStart, element.selectionEnd];
+ element.value = '';
+ const empty = [element.selectionStart, element.selectionEnd];
+ element.value = 'abc';
+ element.setSelectionRange(1, 2, 'backward');
+ element.value = 'abc';
+ const unchanged = [element.selectionStart, element.selectionEnd, element.selectionDirection];
+ element.setSelectionRange = () => { throw new Error('page method called'); };
+ let error = null;
+ try { element.value = 'abcd'; } catch (e) { error = e.message; }
+ return [initial, empty, unchanged, element.value, element.selectionStart, element.selectionEnd, error];
+ });
+ })()"#).unwrap();
+ assert_eq!(value, json!([
+ [[0, 0], [0, 0], [1, 2, "backward"], "abcd", 4, 4, null],
+ [[0, 0], [0, 0], [1, 2, "backward"], "abcd", 4, 4, null]
+ ]));
+}
+
+#[test]
+fn value_assignment_does_not_read_page_attribute_or_text_content_getters() {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(obscura_dom::parse_html("<body></body>"));
+ rt.run_page_init();
+ let value = rt.evaluate(r#"(() => {
+ return ['input', 'textarea'].map(tag => {
+ const element = document.createElement(tag);
+ if (tag === 'textarea') {
+ const descriptor = Object.getOwnPropertyDescriptor(Node.prototype, 'textContent');
+ Object.defineProperty(element, 'textContent', {
+ get() { throw new Error('page getter called'); }, set: descriptor.set
+ });
+ } else {
+ const getAttribute = element.getAttribute;
+ element.getAttribute = function(name) {
+ if (name === 'value') throw new Error('page getter called');
+ return getAttribute.call(this, name);
+ };
+ }
+ try { element.value = 'abc'; return element.value; }
+ catch (e) { return e.message; }
+ });
+ })()"#).unwrap();
+ assert_eq!(value, json!(["abc", "abc"]));
+}
+
+#[test]
+fn set_range_text_converts_unsigned_offsets_before_clamping_to_value_length() {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(obscura_dom::parse_html("<input id='i'>"));
+ rt.run_page_init();
+ let value = rt.evaluate(r#"(() => {
+ const input = document.getElementById('i');
+ return [Infinity, -Infinity, NaN, 4294967296, 4294967297, -1, -1.5, 0.9, '0x1', 1n].map(offset => {
+ input.value = 'abc';
+ try { input.setRangeText('X', offset, offset); return input.value; }
+ catch (e) { return e.name; }
+ });
+ })()"#).unwrap();
+ assert_eq!(value, json!([
+ "Xabc", "Xabc", "Xabc", "Xabc", "aXbc", "abcX", "abcX", "Xabc", "aXbc", "TypeError"
+ ]));
+}
+
#[test]
fn set_range_text_matches_chromium_for_empty_and_nonempty_controls() {
let mut rt = ObscuraJsRuntime::new();