Skip to content

The headless browser for AI agents and web scraping

fix(browser): preserve plain-text document metadata and newlines

SGavrl335f92989d8d
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 26550c19..bfa1d00f 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -280,7 +280,8 @@ pub struct Page {
/// encoding override on `<a>`/`<area>` hrefs in legacy-charset documents.
pub encoding: String,
/// MIME type of the current document's main resource, lowercased and
- /// without parameters. Exposed to JS as `document.contentType`.
+ /// without parameters, or empty when no type was supplied.
+ /// Exposed to JS as `document.contentType`.
pub content_type: String,
/// Monotonic origin for the current document's CSS animation timeline.
/// It is reset once author styles are installed, so stylesheet download
@@ -1116,7 +1117,7 @@ impl Page {
device_scale_factor: 1.0,
default_background_color_override: None,
encoding: "UTF-8".to_string(),
- content_type: "text/html".to_string(),
+ content_type: String::new(),
document_timeline_origin: std::time::Instant::now(),
navigation_timing: NavigationTiming::default(),
navigation_timeout: None,
@@ -3513,7 +3514,7 @@ impl Page {
let (dom, document_content_type) = match plain_text_document_type(response.content_type())
{
Some(mime) => (parse_plain_text_document(&body_text), mime),
- None => (parse_html(&body_text), document_content_type_or_html(response.content_type())),
+ None => (parse_html(&body_text), base_content_type(response.content_type()).unwrap_or_default()),
};
self.content_type = document_content_type;
@@ -3775,6 +3776,7 @@ impl Page {
"<html><head></head><body></body></html>",
));
self.title = String::new();
+ self.content_type.clear();
self.lifecycle = LifecycleState::Loaded;
self.document_timeline_origin = std::time::Instant::now();
}
@@ -5724,6 +5726,40 @@ mod tests {
);
}
+ #[test]
+ fn plain_text_document_preserves_leading_newlines_and_literal_markup() {
+ for (text, expected) in [
+ ("\nfirst\nlast", "\nfirst\nlast"),
+ ("\r\nfirst\rsecond", "\nfirst\nsecond"),
+ ("\n\n", "\n\n"),
+ ("<&amp;> </pre><script>bad()</script>", "<&amp;> </pre><script>bad()</script>"),
+ ] {
+ let dom = super::parse_plain_text_document(text);
+ let pre = dom.query_selector("pre").unwrap().unwrap();
+ assert_eq!(dom.text_content(pre), expected, "input {text:?}");
+ assert!(dom.query_selector("script").unwrap().is_none());
+ }
+ let empty = super::parse_plain_text_document("");
+ assert_eq!(empty.text_content(empty.document()), "");
+ assert!(empty.query_selector("pre").unwrap().is_none());
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn plain_text_navigation_resets_content_type_on_about_blank() {
+ let mut page = super::Page::new(
+ "plain-text-blank".to_string(),
+ std::sync::Arc::new(crate::BrowserContext::new("plain-text-blank".to_string())),
+ );
+ page.navigate("data:text/plain,first%0Alast").await.unwrap();
+ assert_eq!(page.js.as_mut().unwrap().evaluate(
+ "[document.contentType, document.body.textContent]"
+ ).unwrap(), serde_json::json!(["text/plain", "first\nlast"]));
+ page.navigate("about:blank").await.unwrap();
+ assert_eq!(page.js.as_mut().unwrap().evaluate(
+ "[document.contentType, document.body.textContent]"
+ ).unwrap(), serde_json::json!(["text/html", ""]));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn text_markdown_response_keeps_markup_as_text() {
let body = "# Title\n\nSee <Component prop={1} /> and 3 < 4.";
@@ -10349,13 +10385,6 @@ fn base_content_type(content_type: Option<&str>) -> Option<String> {
if ct.is_empty() { None } else { Some(ct) }
}
-/// The MIME type `document.contentType` reports for a main resource. Missing
-/// or empty Content-Type headers stay unset so `contentType` keeps falling
-/// back to URL-derived sniffing.
-fn document_content_type_or_html(content_type: Option<&str>) -> String {
- base_content_type(content_type).unwrap_or_else(|| "text/html".to_string())
-}
-
/// A response whose body is text but not markup gets a plain-text document
/// rather than an HTML parse of its content (`text/plain`, `text/markdown`).
/// Returns the MIME type to report as `document.contentType`.
@@ -10380,14 +10409,13 @@ fn plain_text_document_type(content_type: Option<&str>) -> Option<String> {
/// the whole text. Serializing through the HTML parser keeps one code path for
/// document construction instead of a second native tree builder.
fn parse_plain_text_document(text: &str) -> DomTree {
+ if text.is_empty() {
+ return parse_html("<!DOCTYPE html>");
+ }
let mut html = String::with_capacity(text.len() + 64);
- html.push_str("<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><pre>");
+ // The parser discards the synthetic newline, not the document's first one.
+ html.push_str("<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><pre>\n");
html.push_str(&escape_html_text(text));
- // A newline straight after <pre> is dropped by the HTML parser; an extra
- // one keeps text that itself starts with a newline.
- if text.starts_with('\n') {
- html.push('\n');
- }
html.push_str("</pre></body></html>");
parse_html(&html)
}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index bd20939b..c6eff996 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -5845,6 +5845,8 @@ class Document extends Node {
get charset() { return this.characterSet; }
get inputEncoding() { return this.characterSet; }
get contentType() {
+ const get = _documentRealmMember(this, 'contentType');
+ if (get) return Reflect.apply(get, this, []);
// An explicit type set by DOMParser/createDocument wins.
if (this._contentType) return this._contentType;
// `new Document()` (the WHATWG constructor, no backing node id) creates an
@@ -17241,7 +17243,7 @@ function _installCaretGeometry() {
// Capture late-defined members too, before page code can replace them.
const _nativeElementClick = Element.prototype.click;
const _documentMembers = Object.freeze(Object.fromEntries([
- ...['URL', 'defaultView', 'readyState', 'compatMode', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'write', 'close', 'elementFromPoint', 'queryCommandSupported'].map(name => {
+ ...['URL', 'defaultView', 'readyState', 'compatMode', 'contentType', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'write', 'close', 'elementFromPoint', 'queryCommandSupported'].map(name => {
const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, name);
return [name, descriptor.value || descriptor.get];
}),
diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rs
index c97ae1ad..cfeb283b 100644
--- a/crates/obscura-js/src/frame.rs
+++ b/crates/obscura-js/src/frame.rs
@@ -434,6 +434,23 @@ mod tests {
runtime
}
+ #[test]
+ fn borrowed_content_type_getter_reads_the_frame_document() {
+ let mut parent = ObscuraJsRuntime::new();
+ parent.set_dom(parse_html("<html><body></body></html>"));
+ parent.set_url("https://parent.example/page");
+ parent.set_content_type("text/plain");
+ parent.run_page_init();
+ let _frame = FrameRealm::new(&mut parent, 1, 0,
+ "https://parent.example/frame", "<html><body>Child</body></html>")
+ .expect("frame realm");
+ assert_eq!(parent.evaluate(r#"(function(){
+ const child = globalThis.__obscura_frameObjects[1].document;
+ const get = Object.getOwnPropertyDescriptor(Document.prototype, 'contentType').get;
+ return [get.call(child), child.contentType, document.contentType];
+ })()"#).unwrap(), serde_json::json!(["text/html", "text/html", "text/plain"]));
+ }
+
#[test]
fn fetched_frame_contexts_survive_runtime_teardown_under_gc_stress() {
crate::set_v8_flags("--stress-compaction --stress-marking=1");
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 24dd5638..7b6a21bd 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -430,7 +430,7 @@ impl ObscuraState {
about_base_url: None,
inherited_origin: None,
encoding: "UTF-8".to_string(),
- content_type: "text/html".to_string(),
+ content_type: String::new(),
title: String::new(),
referrer: String::new(),
navigation_timing: NavigationTiming::default(),
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 243bb8d2..b7c574ab 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -4549,6 +4549,16 @@ mod tests {
rt
}
+ #[test]
+ fn document_content_type_retains_url_fallback_without_response_metadata() {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(parse_html("<html><body></body></html>"));
+ rt.set_url("https://example.com/document.xhtml");
+ rt.run_page_init();
+ assert_eq!(rt.evaluate("document.contentType").unwrap(),
+ serde_json::json!("application/xhtml+xml"));
+ }
+
#[test]
fn screen_override_clear_before_page_init_preserves_mutable_hidden_slots() {
let mut rt = ObscuraJsRuntime::new();
diff --git a/docs/Use-with-Playwright.md b/docs/Use-with-Playwright.md
index ccae0a18..237e7d35 100644
--- a/docs/Use-with-Playwright.md
+++ b/docs/Use-with-Playwright.md
@@ -27,6 +27,10 @@ await page.goto('https://example.com', { waitUntil: 'networkidle' });
Default is `domcontentloaded`. Other values: `load`, `networkidle`.
+Navigating to `text/plain`, `text/markdown`, or `text/x-markdown` responses
+preserves literal markup as text instead of parsing it as HTML.
+`document.contentType` reports the response MIME type without parameters.
+
## Evaluate
```js