Skip to content

The headless browser for AI agents and web scraping

fix(cdp): honor beforeinput when inserting text

SGavrld132880ed782
diff --git a/crates/obscura-cdp/src/domains/input.rs b/crates/obscura-cdp/src/domains/input.rs
index 109384c1..d9ced6cb 100644
--- a/crates/obscura-cdp/src/domains/input.rs
+++ b/crates/obscura-cdp/src/domains/input.rs
@@ -21,13 +21,20 @@ fn js_str(s: &str) -> String {
// they left out: a newline inside a single-quoted literal is a syntax error,
// so the whole snippet was dropped and nothing was inserted. obscura-mcp
// already builds its typing snippet this way.
-fn insert_text_js(text: &str) -> String {
+fn insert_text_js(text: &str, ime_commit: bool) -> String {
let literal = serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_string());
format!(
"(function() {{\
var t = document.activeElement;\
if (!t || (t.localName !== 'input' && t.localName !== 'textarea')) return;\
+ if (globalThis.__obscura_isDisabled(t)) return;\
+ if (!{ime_commit} && t.hasAttribute('readonly')) return;\
var ins = {text};\
+ var commitStart = {ime_commit} ? t.selectionStart : null;\
+ if ({ime_commit} && commitStart == null) commitStart = (t.value || '').length;\
+ var before = globalThis.__obscura_markTrusted(new InputEvent('beforeinput', {{bubbles:true,composed:true,cancelable:true,data:ins,inputType:'insertText'}}));\
+ if (!t.dispatchEvent(before)) return;\
+ if (t.hasAttribute('readonly') || globalThis.__obscura_isDisabled(t)) return;\
var v = t.value || '';\
var s = t.selectionStart, e = t.selectionEnd;\
if (s == null) {{\
@@ -37,10 +44,10 @@ fn insert_text_js(text: &str) -> String {
e = (e == null) ? s : Math.max(0, Math.min(e, v.length));\
var lo = Math.min(s, e), hi = Math.max(s, e);\
globalThis.__obscura_setFieldValue(t, 'value', v.slice(0, lo) + ins + v.slice(hi));\
- var caret = lo + ins.length;\
+ var caret = Math.max(0, Math.min((commitStart == null ? lo : commitStart) + ins.length, t.value.length));\
t.setSelectionRange(caret, caret);\
}}\
- t.dispatchEvent(globalThis.__obscura_markTrusted(new Event('input', {{bubbles:true}})));\
+ t.dispatchEvent(globalThis.__obscura_markTrusted(new InputEvent('input', {{bubbles:true,composed:true,data:ins,inputType:'insertText'}})));\
}})()",
text = literal,
)
@@ -397,7 +404,9 @@ pub async fn handle(
"insertText" => {
let text = params.get("text").and_then(|v| v.as_str()).unwrap_or("");
if let Some(page) = ctx.get_session_page_mut(session_id) {
- page.evaluate(&insert_text_js(text));
+ // IME commits snapshot the final caret before beforeinput.
+ // Keyboard insertion instead follows the handler's selection.
+ page.evaluate(&insert_text_js(text, true));
}
Ok(json!({}))
}
@@ -433,7 +442,7 @@ pub async fn handle(
page.evaluate(&js);
if !text.is_empty() && text != "\r" && text != "\n" {
- page.evaluate(&insert_text_js(text));
+ page.evaluate(&insert_text_js(text, false));
}
if key == "Enter" {
@@ -486,7 +495,7 @@ pub async fn handle(
}
"char" => {
if !text.is_empty() {
- page.evaluate(&insert_text_js(text));
+ page.evaluate(&insert_text_js(text, false));
// Pump event loop so Angular change detection picks up the input
page.settle(50).await;
}
diff --git a/crates/obscura-cdp/tests/textarea_enter_selection.rs b/crates/obscura-cdp/tests/textarea_enter_selection.rs
index a5c4b877..1bb6bd86 100644
--- a/crates/obscura-cdp/tests/textarea_enter_selection.rs
+++ b/crates/obscura-cdp/tests/textarea_enter_selection.rs
@@ -108,3 +108,78 @@ async fn typing_continues_after_the_inserted_newline() {
assert_eq!(result["start"], 3);
assert_eq!(result["end"], 3);
}
+
+#[tokio::test(flavor = "current_thread")]
+async fn text_insertion_dispatches_cancelable_beforeinput_and_trusted_input_events() {
+ let mut ctx = setup().await;
+ for tag in ["input", "textarea"] {
+ for (method, params) in [
+ ("Input.insertText", json!({"text": "Z"})),
+ ("Input.dispatchKeyEvent", json!({"type": "keyDown", "key": "Z", "text": "Z"})),
+ ("Input.dispatchKeyEvent", json!({"type": "char", "text": "Z"})),
+ ] {
+ evaluate(&mut ctx, &format!(r#"(function() {{
+ document.body.innerHTML = '<{tag} id="field"></{tag}>';
+ var field = document.getElementById('field');
+ field.value = 'abCD'; field.focus(); field.setSelectionRange(1, 3);
+ globalThis.editEvents = [];
+ for (var type of ['beforeinput', 'input']) field.addEventListener(type, function(e) {{
+ editEvents.push([e.type, e instanceof InputEvent, e.data, e.inputType,
+ e.isTrusted, e.bubbles, e.composed, e.cancelable, field.value]);
+ }});
+ }})()"#)).await;
+ cdp(&mut ctx, method, params).await;
+ assert_eq!(evaluate(&mut ctx, "document.getElementById('field').value").await, "aZD");
+ assert_eq!(evaluate(&mut ctx, "editEvents").await, json!([
+ ["beforeinput", true, "Z", "insertText", true, true, true, true, "abCD"],
+ ["input", true, "Z", "insertText", true, true, true, false, "aZD"]
+ ]), "{tag}: {method}");
+ }
+ }
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn canceled_or_readonly_text_insertion_preserves_value_and_selection() {
+ let mut ctx = setup().await;
+ for tag in ["input", "textarea"] {
+ for guard in [
+ "field.addEventListener('beforeinput', function(e) { e.preventDefault(); });",
+ "field.readOnly = true;",
+ "field.setAttribute('readonly', '');",
+ ] {
+ evaluate(&mut ctx, &format!(r#"(function() {{
+ document.body.innerHTML = '<{tag} id="field"></{tag}>';
+ var field = document.getElementById('field');
+ field.value = 'abCD'; field.focus(); field.setSelectionRange(1, 3);
+ globalThis.editEvents = [];
+ for (var type of ['beforeinput', 'input']) field.addEventListener(type, function(e) {{
+ editEvents.push(e.type);
+ }});
+ {guard}
+ }})()"#)).await;
+ cdp(&mut ctx, "Input.insertText", json!({"text": "Z"})).await;
+ assert_eq!(evaluate(&mut ctx, "(function() { var field = document.getElementById('field'); return [field.value, field.selectionStart, field.selectionEnd, editEvents]; })()").await,
+ json!(["abCD", 1, 3, ["beforeinput"]]), "{tag}: {guard}");
+ }
+ }
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn text_insertion_reads_value_and_selection_after_beforeinput_handlers() {
+ let mut ctx = setup().await;
+ evaluate(&mut ctx, r#"field.addEventListener('beforeinput', function() {
+ field.value = 'xy'; field.setSelectionRange(0, 1);
+ });"#).await;
+ for (method, params, caret) in [
+ ("Input.insertText", json!({"text": "Z"}), 2),
+ ("Input.dispatchKeyEvent", json!({"type": "keyDown", "key": "Z", "text": "Z"}), 1),
+ ("Input.dispatchKeyEvent", json!({"type": "char", "text": "Z"}), 1),
+ ] {
+ evaluate(&mut ctx, "field.value = 'abCD'; field.setSelectionRange(1, 3);").await;
+ cdp(&mut ctx, method, params).await;
+ let result = state(&mut ctx).await;
+ assert_eq!(result["value"], "Zy");
+ assert_eq!(result["start"], caret, "{method}");
+ assert_eq!(result["end"], caret, "{method}");
+ }
+}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 2d47383f..bd5a7103 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -12765,7 +12765,10 @@ globalThis.HTMLSpanElement = Element;
globalThis.HTMLParagraphElement = Element;
globalThis.HTMLAnchorElement = Element;
globalThis.HTMLImageElement = HTMLImageElement;
-globalThis.HTMLInputElement = class HTMLInputElement extends Element {};
+globalThis.HTMLInputElement = class HTMLInputElement extends Element {
+ get readOnly() { return this.hasAttribute('readonly'); }
+ set readOnly(v) { if (v) this.setAttribute('readonly', ''); else this.removeAttribute('readonly'); }
+};
// Framework value trackers read own prototype descriptors, not inherited ones.
Object.defineProperties(HTMLInputElement.prototype, {
value: Object.getOwnPropertyDescriptor(Element.prototype, 'value'),
@@ -12796,6 +12799,8 @@ globalThis.HTMLFormElement = class HTMLFormElement extends Element {
};
globalThis.HTMLSelectElement = Element;
globalThis.HTMLTextAreaElement = class HTMLTextAreaElement extends Element {
+ get readOnly() { return this.hasAttribute('readonly'); }
+ set readOnly(v) { if (v) this.setAttribute('readonly', ''); else this.removeAttribute('readonly'); }
// `rows`/`cols` reflect the content attributes and drive the control's
// intrinsic box (the renderer sizes a textarea from them). The attributes
// are limited to positive non-zero numbers; anything else falls back to the
@@ -12813,6 +12818,9 @@ globalThis.HTMLTextAreaElement = class HTMLTextAreaElement extends Element {
set cols(v) { this.setAttribute('cols', String(v)); }
};
globalThis.HTMLLabelElement = Element;
+for (const proto of [HTMLInputElement.prototype, HTMLTextAreaElement.prototype]) {
+ Object.defineProperty(proto, 'readOnly', { enumerable: true });
+}
globalThis.HTMLTableElement = Element;
globalThis.HTMLIFrameElement = Element;
globalThis.HTMLCanvasElement = Element;
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 63b62b18..7f3387ba 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -8321,6 +8321,35 @@ mod tests {
]));
}
+ #[test]
+ fn readonly_controls_reflect_boolean_attributes_without_polluting_other_elements() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt.evaluate(r#"
+ const enumerated = [];
+ const states = ['input', 'textarea'].map(tag => {
+ const field = document.createElement(tag);
+ const values = [[field.readOnly, field.getAttribute('readonly')]];
+ field.readOnly = true;
+ values.push([field.readOnly, field.getAttribute('readonly')]);
+ field.readOnly = false;
+ values.push([field.readOnly, field.getAttribute('readonly')]);
+ field.setAttribute('readonly', 'false');
+ values.push([field.readOnly, field.getAttribute('readonly')]);
+ field.removeAttribute('readonly');
+ values.push([field.readOnly, field.getAttribute('readonly')]);
+ for (const key in field) if (key === 'readOnly') enumerated.push(field[key]);
+ return values;
+ });
+ return [states, 'readOnly' in document.createElement('div'), enumerated];
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!([
+ [
+ [[false, null], [true, ""], [false, null], [true, "false"], [false, null]],
+ [[false, null], [true, ""], [false, null], [true, "false"], [false, null]]
+ ], false, [false, false]
+ ]));
+ }
+
#[test]
fn hyperlink_content_attributes_reflect_through_the_idl_surface() {
let mut rt = setup_runtime(