Skip to content

The headless browser for AI agents and web scraping

fix(cdp): honor color-scheme media overrides

vvinayakkkc7ec60a9e521
diff --git a/README.md b/README.md
index 6ccf4b2b..a5c74481 100644
--- a/README.md
+++ b/README.md
@@ -328,6 +328,8 @@ obscura --proxy http://127.0.0.1:8080 scrape https://example.com https://news.yc
## Puppeteer / Playwright
+[Media preference emulation](docs/CDP-media.md) covers color-scheme and reduced-motion overrides.
+
### Puppeteer
```bash
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index fbdc129b..9796fd2b 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -267,6 +267,7 @@ pub struct Page {
/// only when the override is cleared.
device_metrics_baseline: Option<DeviceMetricsBaseline>,
reduced_motion: bool,
+ dark_color_scheme: bool,
/// Output device pixels per CSS pixel for CDP surface capture. Layout and
/// CSSOM stay in CSS pixels; Emulation.setDeviceMetricsOverride owns this
/// independent raster scale.
@@ -1110,6 +1111,7 @@ impl Page {
locale_override: None,
device_metrics_baseline: None,
reduced_motion: false,
+ dark_color_scheme: false,
device_scale_factor: 1.0,
default_background_color_override: None,
encoding: "UTF-8".to_string(),
@@ -1695,6 +1697,16 @@ impl Page {
self.set_device_scale_factor(baseline.device_scale_factor);
}
+ /// Override reduced-motion and dark color-scheme preferences together.
+ /// The pair persists across navigation and is shared with child documents.
+ pub fn set_media_preferences(&mut self, reduce: bool, dark: bool) {
+ self.reduced_motion = reduce;
+ self.dark_color_scheme = dark;
+ if let Some(js) = &mut self.js {
+ js.set_media_preferences(reduce, dark);
+ }
+ }
+
pub fn set_reduced_motion(&mut self, reduce: bool) {
self.reduced_motion = reduce;
if let Some(js) = &mut self.js {
@@ -1855,7 +1867,7 @@ impl Page {
rt.set_navigation_timing(self.navigation_timing.clone());
rt.run_page_init();
- rt.set_reduced_motion(self.reduced_motion);
+ rt.set_media_preferences(self.reduced_motion, self.dark_color_scheme);
let _ = rt.execute_script(
"<device-metrics>",
&format!("globalThis.devicePixelRatio={};", self.device_scale_factor),
diff --git a/crates/obscura-browser/src/pdf.rs b/crates/obscura-browser/src/pdf.rs
index d292c58b..a9898649 100644
--- a/crates/obscura-browser/src/pdf.rs
+++ b/crates/obscura-browser/src/pdf.rs
@@ -311,7 +311,8 @@ impl Page {
return Err(RasterPdfError::NoRenderableDocument);
}
let previous_media = js.set_render_media(
- obscura_js::CssMediaType::Print.with_reduced_motion(js.prefers_reduced_motion()),
+ obscura_js::CssMediaType::Print.with_reduced_motion(js.prefers_reduced_motion())
+ .with_dark_color_scheme(js.prefers_dark_color_scheme()),
);
let result = (|| {
let (content_width, content_height) = js
@@ -937,6 +938,48 @@ mod tests {
);
}
+ #[test]
+ fn raster_pdf_preserves_emulated_color_scheme_and_restores_screen() {
+ let context = std::sync::Arc::new(crate::BrowserContext::new("pdf-color".into()));
+ let mut page = crate::Page::new("pdf-color-page".into(), context);
+ page.set_viewport((100.0, 80.0));
+ let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
+ runtime.set_dom(obscura_dom::parse_html(r#"<!doctype html><style>
+ html,body { margin:0 }
+ #probe { width:100px;height:80px;background:#ffffff }
+ @media (prefers-color-scheme:dark) { #probe { background:#e02020 } }
+ @media print and (prefers-color-scheme:dark) and (prefers-reduced-motion:reduce) {
+ #probe { background:#2050e0 }
+ }
+ </style><body><div id="probe"></div></body>"#));
+ runtime.set_url("https://example.test/pdf-color");
+ page.url = Some(url::Url::parse("https://example.test/pdf-color").unwrap());
+ runtime.set_viewport(100.0, 80.0);
+ runtime.run_page_init();
+ page.js = Some(runtime);
+ page.set_media_preferences(true, true);
+ let before = page.screenshot((100.0, 80.0)).unwrap();
+ let pixels = image::load_from_memory(&before).unwrap().into_rgb8();
+ assert_eq!(pixels.get_pixel(50, 60).0, [224, 32, 32]);
+ let ad_hoc = page.screenshot((120.0, 90.0)).unwrap();
+ let ad_hoc = image::load_from_memory(&ad_hoc).unwrap().into_rgb8();
+ assert_eq!(ad_hoc.dimensions(), (120, 90));
+ assert_eq!(ad_hoc.get_pixel(50, 60).0, [224, 32, 32]);
+ let options = RasterPdfOptions {
+ print_background: true,
+ paper_width_in: 100.0 / POINTS_PER_INCH,
+ paper_height_in: 80.0 / POINTS_PER_INCH,
+ margin_top_in: 0.0, margin_bottom_in: 0.0,
+ margin_left_in: 0.0, margin_right_in: 0.0,
+ ..RasterPdfOptions::default()
+ };
+ let pages = pdf_page_rasters(&page.raster_pdf(options).unwrap());
+ assert_eq!(pages.len(), 1);
+ assert!(channel_near(*pages[0].get_pixel(50, 60), [32, 80, 224]));
+ assert_eq!(page.screenshot((100.0, 80.0)).unwrap(), before);
+ assert_eq!(page.evaluate("return matchMedia('(prefers-color-scheme:dark)').matches;"), serde_json::json!(true));
+ }
+
#[test]
fn writer_emits_xref_and_one_image_per_page() {
let pdf = encode_pdf_pages(1, 612.0, 792.0, 36.0, 36.0, 720.0, |_| {
diff --git a/crates/obscura-cdp/src/domains/emulation.rs b/crates/obscura-cdp/src/domains/emulation.rs
index 42cedd9a..6af21045 100644
--- a/crates/obscura-cdp/src/domains/emulation.rs
+++ b/crates/obscura-cdp/src/domains/emulation.rs
@@ -66,16 +66,35 @@ pub async fn handle(
) -> Result<Value, String> {
match method {
"setEmulatedMedia" => {
- let features = params.get("features").and_then(Value::as_array);
- if let Some(features) = features {
- let value = features.iter().find(|feature| feature["name"] == "prefers-reduced-motion")
- .and_then(|feature| feature["value"].as_str()).unwrap_or("");
- if !matches!(value, "" | "reduce" | "no-preference") {
- return Err("Invalid prefers-reduced-motion value".into());
+ let features = match params.get("features") {
+ Some(features) => features.as_array().ok_or("Emulation.setEmulatedMedia features must be an array")?.as_slice(),
+ None => &[],
+ };
+ let mut reduce = false;
+ let mut dark = false;
+ for feature in features {
+ let name = feature.get("name").and_then(Value::as_str)
+ .ok_or("Media feature requires a string name")?;
+ let value = feature.get("value").and_then(Value::as_str)
+ .ok_or("Media feature requires a string value")?;
+ match name {
+ "prefers-reduced-motion" => {
+ if !matches!(value, "" | "reduce" | "no-preference") {
+ return Err("Invalid prefers-reduced-motion value".into());
+ }
+ reduce = value == "reduce";
+ }
+ "prefers-color-scheme" => {
+ if !matches!(value, "" | "dark" | "light" | "no-preference") {
+ return Err("Invalid prefers-color-scheme value".into());
+ }
+ dark = value == "dark";
+ }
+ _ => {}
}
- ctx.get_session_page_mut(session_id).ok_or("No page for session")?
- .set_reduced_motion(value == "reduce");
}
+ ctx.get_session_page_mut(session_id).ok_or("No page for session")?
+ .set_media_preferences(reduce, dark);
Ok(json!({}))
}
"setDeviceMetricsOverride" => {
@@ -181,6 +200,45 @@ pub async fn handle(
mod tests {
use super::*;
+ #[tokio::test]
+ async fn color_scheme_override_persists_and_resets_without_partial_invalid_updates() {
+ let mut ctx = CdpContext::new();
+ let id = ctx.create_page();
+ let session = Some("media-session".to_string());
+ ctx.sessions.insert(session.clone().unwrap(), id);
+ let both = json!({"features": [
+ {"name": "prefers-color-scheme", "value": "dark"},
+ {"name": "prefers-reduced-motion", "value": "reduce"}
+ ]});
+ handle("setEmulatedMedia", &both, &mut ctx, &session).await.unwrap();
+ let script = "return [matchMedia('(prefers-color-scheme:dark)').matches, matchMedia('(prefers-reduced-motion:reduce)').matches];";
+ for _ in 0..2 {
+ let page = ctx.get_session_page_mut(&session).unwrap();
+ page.navigate("data:text/html,<body>probe</body>").await.unwrap();
+ assert_eq!(page.evaluate(script), json!([true, true]));
+ }
+ for invalid in [
+ json!({"features": null}),
+ json!({"features": [{"name":"prefers-color-scheme", "value":false}]}),
+ json!({"features": [{"name":"prefers-color-scheme", "value":"light"}, {"name":"prefers-reduced-motion", "value":"invalid"}]}),
+ json!({"features": [{"name":"prefers-color-scheme", "value":"invalid"}]}),
+ ] {
+ assert!(handle("setEmulatedMedia", &invalid, &mut ctx, &session).await.is_err());
+ assert_eq!(ctx.get_session_page_mut(&session).unwrap().evaluate(script), json!([true, true]));
+ }
+ handle("setEmulatedMedia", &json!({}), &mut ctx, &session).await.unwrap();
+ assert_eq!(ctx.get_session_page_mut(&session).unwrap().evaluate(script), json!([false, false]));
+ handle("setEmulatedMedia", &both, &mut ctx, &session).await.unwrap();
+ for value in ["light", "no-preference", ""] {
+ handle("setEmulatedMedia", &json!({"features":[{"name":"prefers-color-scheme", "value":value}]}), &mut ctx, &session).await.unwrap();
+ assert_eq!(ctx.get_session_page_mut(&session).unwrap().evaluate(script), json!([false, false]));
+ handle("setEmulatedMedia", &both, &mut ctx, &session).await.unwrap();
+ }
+ handle("setEmulatedMedia", &json!({"features":[]}), &mut ctx, &session).await.unwrap();
+ assert_eq!(ctx.get_session_page_mut(&session).unwrap().evaluate(script), json!([false, false]));
+ }
+
+
#[tokio::test]
async fn device_metrics_override_updates_page_and_window_viewport() {
let mut ctx = CdpContext::new();
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index be457daf..8bf1e5b9 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -609,7 +609,6 @@ function _rebaseCssUrls(css, baseUrl) {
function _cssImportApplies(media) {
const compact = media.replace(/\s+/g, "").toLowerCase();
if (!compact) return true;
- if (compact.includes("prefers-color-scheme:dark")) return false;
if (compact.includes("print")
&& !compact.includes("screen")
&& !compact.includes("all")) return false;
@@ -9041,6 +9040,9 @@ function _evaluateMediaDimension(feature) {
return null;
}
+let _prefersDark = false;
+let _prefersReducedMotion = false;
+
function _evaluateMediaFeature(raw) {
let feature = raw.trim().toLowerCase();
if (feature[0] !== '(' || feature[feature.length - 1] !== ')') return false;
@@ -9056,10 +9058,11 @@ function _evaluateMediaFeature(raw) {
return match[1] === 'portrait' ? height >= width : width > height;
}
+ if (feature === 'prefers-color-scheme') return true;
match = feature.match(/^prefers-color-scheme\s*:\s*(dark|light|no-preference)$/);
- if (match) return match[1] === 'light';
+ if (match) return match[1] === (_prefersDark ? 'dark' : 'light');
match = feature.match(/^prefers-reduced-motion\s*:\s*(reduce|no-preference)$/);
- if (match) return match[1] === (globalThis.__obscura_reduced_motion ? 'reduce' : 'no-preference');
+ if (match) return match[1] === (_prefersReducedMotion ? 'reduce' : 'no-preference');
match = feature.match(/^(pointer|any-pointer)\s*:\s*(none|coarse|fine)$/);
if (match) return match[2] === 'fine';
@@ -9122,6 +9125,11 @@ const _mediaQueries = new Set();
// code does not retain the object returned from matchMedia().
const _activeMediaQueries = new Set();
const _mediaQueryState = new WeakMap();
+globalThis.__obscura_update_media_preferences = () => {
+ _prefersDark = !!_domParse("prefers_dark");
+ _prefersReducedMotion = !!_domParse("prefers_reduced_motion");
+ globalThis.__obscura_recompute_media_queries();
+};
globalThis.__obscura_recompute_media_queries = () => {
// Media/viewport changes also invalidate live computed-style snapshots.
// Keep the epoch in this private scope, not in host-injected page script.
@@ -17221,6 +17229,7 @@ const _documentMembers = Object.freeze(Object.fromEntries([
globalThis.__obscura_init = function() {
// The host sets __obscura_frameId on a frame realm before calling this.
_realmFrameId = globalThis.__obscura_frameId >>> 0;
+ globalThis.__obscura_update_media_preferences();
const caretMembers = _installCaretGeometry();
__obscuraCore.ops.op_register_document_realm(
Object.keys(caretMembers).length ? Object.freeze({ ..._documentMembers, ...caretMembers }) : _documentMembers,
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index d1863686..1e6f3bd5 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -160,6 +160,8 @@ pub struct ObscuraState {
/// encoding override for `<a>`/`<area>` hrefs in legacy-charset documents.
pub encoding: String,
pub title: String,
+ /// (reduced motion, dark scheme), shared by every document in this page.
+ pub(crate) media_preferences: Rc<Cell<(bool, bool)>>,
/// URL of the document that initiated this document's navigation. Direct
/// browser/API navigations leave this empty; document-initiated
/// navigations set it to the source document URL.
@@ -397,6 +399,12 @@ pub struct PendingFrameMessage {
impl ObscuraState {
pub(crate) fn inherit_resources(&mut self, parent: &Self) {
+ self.media_preferences = parent.media_preferences.clone();
+ #[cfg(feature = "render")]
+ {
+ let (reduce, dark) = parent.media_preferences.get();
+ self.render_media = self.render_media.with_reduced_motion(reduce).with_dark_color_scheme(dark);
+ }
self.cookie_jar = parent.cookie_jar.clone();
self.http_client = parent.http_client.clone();
self.callbacks = parent.callbacks.clone();
@@ -424,6 +432,7 @@ impl ObscuraState {
inherited_origin: None,
encoding: "UTF-8".to_string(),
title: String::new(),
+ media_preferences: Rc::new(Cell::new((false, false))),
referrer: String::new(),
navigation_timing: NavigationTiming::default(),
blocked_urls: Vec::new(),
@@ -891,6 +900,10 @@ struct FrameTimers {
}
impl RealmStates {
+ pub(crate) fn media_realms(&self) -> Vec<(v8::Global<v8::Context>, SharedState)> {
+ self.entries.iter().map(|(context, _, state)| (context.clone(), state.clone())).collect()
+ }
+
pub(crate) fn live_count(&self) -> usize {
self.entries.len()
}
@@ -1885,6 +1898,12 @@ fn op_dom(
}
fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) -> String {
+ if cmd == "prefers_reduced_motion" {
+ return shared.borrow().media_preferences.get().0.to_string();
+ }
+ if cmd == "prefers_dark" {
+ return shared.borrow().media_preferences.get().1.to_string();
+ }
if cmd == "performance_time_origin" {
return shared.borrow().navigation_timing.time_origin.to_string();
}
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 462153a3..6a30465d 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -1465,17 +1465,42 @@ impl ObscuraJsRuntime {
);
}
- /// Keep JavaScript media queries and CSS selection on the same preference.
- pub fn set_reduced_motion(&mut self, reduce: bool) {
+ /// Apply preference overrides together so compound query listeners observe
+ /// one media change, including in existing child documents.
+ pub fn set_media_preferences(&mut self, reduce: bool, dark: bool) {
+ self.state.borrow().media_preferences.set((reduce, dark));
+ let realms = self.realm_states().borrow().media_realms();
#[cfg(feature = "render")]
{
- let media = self.state.borrow().render_media.with_reduced_motion(reduce);
+ let media = self.state.borrow().render_media
+ .with_reduced_motion(reduce).with_dark_color_scheme(dark);
self.set_render_media(media);
+ for (_, state) in &realms {
+ let mut state = state.borrow_mut();
+ let media = state.render_media.with_reduced_motion(reduce).with_dark_color_scheme(dark);
+ if state.render_media != media {
+ state.render_media = media;
+ state.prepared_render = None;
+ state.resolved_scroll = None;
+ }
+ }
+ }
+ let script = "globalThis.__obscura_update_media_preferences();";
+ let _ = self.execute_runtime_script("<media-preferences>", script.into());
+ for (context, _) in realms {
+ let _ = self.eval_in_realm(&context, script);
}
- let _ = self.execute_runtime_script("<reduced-motion>", format!(
- "globalThis.__obscura_reduced_motion={reduce};\
- globalThis.__obscura_recompute_media_queries();"
- ));
+ }
+
+ #[cfg(feature = "render")]
+ pub fn prefers_dark_color_scheme(&self) -> bool {
+ self.state.borrow().media_preferences.get().1
+ }
+
+ /// Keep JavaScript media queries and CSS selection on the same preference.
+ pub fn set_reduced_motion(&mut self, reduce: bool) {
+ let dark = self.state.borrow().media_preferences.get().1;
+ self.set_media_preferences(reduce, dark);
}
/// Override the physical screen metrics exposed to page JavaScript.
@@ -1635,8 +1660,27 @@ impl ObscuraJsRuntime {
let ObscuraState {
dom,
render_resources,
+ render_media,
+ dynamic_fonts,
..
} = &mut *state;
+ // An ad-hoc capture must select the same preference rules as CSSOM.
+ // Keep its viewport-specific cascade separate from the live cache.
+ if *render_media != obscura_render::CssMediaType::Screen {
+ let tree = dom.as_ref()?;
+ let mut cache = obscura_render::StylesheetCache::default();
+ let mut timeline = obscura_render::AnimationTimelineState::default();
+ let mut prepared = obscura_render::prepare_dom_with_dynamic_fonts_and_stylesheet_cache_for_media_with_animation_state(
+ tree, viewport, base_url, render_resources, dynamic_fonts,
+ &mut cache, *render_media,
+ obscura_render::AnimationSample::local_override(animation_sample_time.milliseconds),
+ &mut timeline,
+ )?;
+ let resolved = prepared.resolve_scroll_state(tree, scroll, &Default::default());
+ return obscura_render::screenshot_prepared_with_scroll_and_surface_color(
+ tree, &mut prepared, render_resources, &resolved, surface_color,
+ );
+ }
obscura_render::screenshot_png_scrolled_at_animation_time_with_surface_color_and_resources(
dom.as_ref()?,
viewport,
diff --git a/crates/obscura-js/tests/color_scheme.rs b/crates/obscura-js/tests/color_scheme.rs
new file mode 100644
index 00000000..009574d3
--- /dev/null
+++ b/crates/obscura-js/tests/color_scheme.rs
@@ -0,0 +1,100 @@
+use obscura_js::runtime::ObscuraJsRuntime;
+use serde_json::json;
+
+fn runtime() -> ObscuraJsRuntime {
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(obscura_dom::parse_html("<!doctype html><body></body>"));
+ rt.run_page_init();
+ rt
+}
+
+#[tokio::test]
+async fn color_scheme_updates_compound_queries_once_and_clears() {
+ let mut rt = runtime();
+ rt.evaluate(r#"(() => {
+ globalThis.q = matchMedia('(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)');
+ globalThis.changes = [];
+ q.addListener(e => changes.push(e.matches));
+ globalThis.probe = () => ['dark', 'light', 'no-preference'].map(v =>
+ matchMedia('(prefers-color-scheme: ' + v + ')').matches);
+ })()"#).unwrap();
+ assert_eq!(rt.evaluate("probe()").unwrap(), json!([false, true, false]));
+ assert_eq!(rt.evaluate("[matchMedia('(prefers-color-scheme)').matches, matchMedia('(prefers-color-scheme:invalid)').matches]").unwrap(), json!([true, false]));
+ rt.set_media_preferences(true, true);
+ rt.run_event_loop_bounded(30).await.unwrap();
+ rt.set_media_preferences(true, true);
+ rt.run_event_loop_bounded(30).await.unwrap();
+ assert_eq!(
+ rt.evaluate("[probe(), changes]").unwrap(),
+ json!([[true, false, false], [true]])
+ );
+ rt.set_reduced_motion(false);
+ assert_eq!(rt.evaluate("probe()").unwrap(), json!([true, false, false]));
+ rt.set_media_preferences(false, false);
+ rt.run_event_loop_bounded(30).await.unwrap();
+ assert_eq!(
+ rt.evaluate("[probe(), changes]").unwrap(),
+ json!([[false, true, false], [true, false]])
+ );
+}
+
+#[tokio::test]
+async fn color_scheme_reaches_existing_and_new_child_documents() {
+ let mut rt = runtime();
+ rt.evaluate(r#"(() => {
+ const f = document.createElement('iframe'); document.body.appendChild(f);
+ globalThis.child = f.contentWindow;
+ child.eval("globalThis.q = matchMedia('(prefers-color-scheme: dark)'); globalThis.changes = []; q.onchange = e => changes.push(e.matches)");
+ })()"#).unwrap();
+ rt.set_media_preferences(true, true);
+ rt.run_event_loop_bounded(30).await.unwrap();
+ assert_eq!(
+ rt.evaluate("[child.q.matches, child.changes]").unwrap(),
+ json!([true, [true]])
+ );
+ assert_eq!(rt.evaluate(r#"(() => {
+ const f = document.createElement('iframe'); document.body.appendChild(f);
+ return f.contentWindow.matchMedia('(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)').matches;
+ })()"#).unwrap(), json!(true));
+ rt.set_media_preferences(false, false);
+ rt.run_event_loop_bounded(30).await.unwrap();
+ assert_eq!(
+ rt.evaluate("[child.q.matches, child.changes]").unwrap(),
+ json!([false, [true, false]])
+ );
+}
+
+#[cfg(feature = "render")]
+#[test]
+fn color_scheme_invalidates_live_styles_geometry_and_print_selection() {
+ let mut rt = runtime();
+ rt.evaluate(r#"(() => {
+ document.body.innerHTML = '<style>div{width:100px;color:rgb(1,2,3)}@media(prefers-color-scheme:dark){div{width:40px;color:rgb(4,5,6)}}@media print and (prefers-color-scheme:dark){div{width:60px}}</style><div>probe</div>';
+ globalThis.box = document.querySelector('div'); globalThis.live = getComputedStyle(box);
+ globalThis.probe = () => [live.color, live.width, box.getBoundingClientRect().width];
+ })()"#).unwrap();
+ assert_eq!(
+ rt.evaluate("probe()").unwrap(),
+ json!(["rgb(1, 2, 3)", "100px", 100])
+ );
+ rt.set_media_preferences(true, true);
+ assert_eq!(
+ rt.evaluate("probe()").unwrap(),
+ json!(["rgb(4, 5, 6)", "40px", 40])
+ );
+ let previous = rt.set_render_media(
+ obscura_js::CssMediaType::Print
+ .with_reduced_motion(true)
+ .with_dark_color_scheme(true),
+ );
+ assert_eq!(
+ rt.evaluate("box.getBoundingClientRect().width").unwrap(),
+ json!(60.0)
+ );
+ rt.set_render_media(previous);
+ rt.set_media_preferences(false, false);
+ assert_eq!(
+ rt.evaluate("probe()").unwrap(),
+ json!(["rgb(1, 2, 3)", "100px", 100])
+ );
+}
diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rs
index 82a9f6ce..26f08ef2 100644
--- a/crates/obscura-render/src/css.rs
+++ b/crates/obscura-render/src/css.rs
@@ -27,20 +27,47 @@ pub enum CssMediaType {
Print,
ScreenReducedMotion,
PrintReducedMotion,
+ ScreenDark,
+ PrintDark,
+ ScreenDarkReducedMotion,
+ PrintDarkReducedMotion,
}
impl CssMediaType {
pub fn with_reduced_motion(self, reduce: bool) -> Self {
- match (self, reduce) {
- (Self::Print | Self::PrintReducedMotion, false) => Self::Print,
- (Self::Print | Self::PrintReducedMotion, true) => Self::PrintReducedMotion,
- (_, false) => Self::Screen,
- (_, true) => Self::ScreenReducedMotion,
+ match (self.is_print(), reduce, self.dark_color_scheme()) {
+ (false, false, false) => Self::Screen,
+ (false, true, false) => Self::ScreenReducedMotion,
+ (true, false, false) => Self::Print,
+ (true, true, false) => Self::PrintReducedMotion,
+ (false, false, true) => Self::ScreenDark,
+ (false, true, true) => Self::ScreenDarkReducedMotion,
+ (true, false, true) => Self::PrintDark,
+ (true, true, true) => Self::PrintDarkReducedMotion,
}
}
+ pub fn with_dark_color_scheme(self, dark: bool) -> Self {
+ let medium = if self.is_print() { Self::Print } else { Self::Screen };
+ let medium = if dark {
+ if medium.is_print() { Self::PrintDark } else { Self::ScreenDark }
+ } else { medium };
+ medium.with_reduced_motion(self.reduced_motion())
+ }
+
pub fn reduced_motion(self) -> bool {
- matches!(self, Self::ScreenReducedMotion | Self::PrintReducedMotion)
+ matches!(self, Self::ScreenReducedMotion | Self::PrintReducedMotion
+ | Self::ScreenDarkReducedMotion | Self::PrintDarkReducedMotion)
+ }
+
+ pub fn dark_color_scheme(self) -> bool {
+ matches!(self, Self::ScreenDark | Self::PrintDark
+ | Self::ScreenDarkReducedMotion | Self::PrintDarkReducedMotion)
+ }
+
+ pub fn is_print(self) -> bool {
+ matches!(self, Self::Print | Self::PrintReducedMotion
+ | Self::PrintDark | Self::PrintDarkReducedMotion)
}
}
@@ -6864,8 +6891,8 @@ fn single_media_query_applies_for_viewport(
let medium = compact.split_once("and").map_or(compact, |(medium, _)| medium);
let medium_matches = match medium {
"all" => true,
- "screen" => matches!(media_type, CssMediaType::Screen | CssMediaType::ScreenReducedMotion),
- "print" => matches!(media_type, CssMediaType::Print | CssMediaType::PrintReducedMotion),
+ "screen" => !media_type.is_print(),
+ "print" => media_type.is_print(),
medium if medium.starts_with('(') => true,
// Unknown named media such as `speech` do not match either visual
// rendering mode.
@@ -6875,12 +6902,14 @@ fn single_media_query_applies_for_viewport(
return false;
}
- // Color-scheme: we render the light (default) context. A site's
- // `@media (prefers-color-scheme: dark)` block must NOT apply on top of its
- // light defaults (that is what was leaking dark backgrounds, e.g. near
- // black inline <code>); a `:light` block should apply.
- if compact.contains("prefers-color-scheme:dark") {
- return false;
+ for feature in compact.split('(') {
+ if let Some(value) = feature.strip_prefix("prefers-color-scheme:") {
+ let value = value.split(')').next().unwrap_or(value);
+ let expected = if media_type.dark_color_scheme() { "dark" } else { "light" };
+ if value != expected {
+ return false;
+ }
+ }
}
// Reduced-motion / high-contrast / inverted: default (no preference).
if (compact.contains("prefers-reduced-motion:reduce") && !media_type.reduced_motion())
@@ -10272,6 +10301,30 @@ mod tests {
));
}
+ #[test]
+ fn media_color_scheme_preserves_motion_and_medium() {
+ for medium in [CssMediaType::Screen, CssMediaType::Print] {
+ for reduce in [false, true] {
+ for dark in [false, true] {
+ let media = medium.with_reduced_motion(reduce).with_dark_color_scheme(dark);
+ assert_eq!(media.reduced_motion(), reduce);
+ assert_eq!(media.is_print(), medium.is_print());
+ assert_eq!(media.dark_color_scheme(), dark);
+ let applies = |q| media_query_applies_for_viewport_and_type(q, (800.0, 600.0), media);
+ assert_eq!(applies("(prefers-color-scheme:dark)"), dark);
+ assert_eq!(applies("(prefers-color-scheme:light)"), !dark);
+ assert!(!applies("(prefers-color-scheme:no-preference)"));
+ assert!(!applies("(prefers-color-scheme:invalid)"));
+ assert!(applies("(prefers-color-scheme)"));
+ assert_eq!(applies("not all and (prefers-color-scheme:dark)"), !dark);
+ assert_eq!(applies("(prefers-color-scheme:dark) and (prefers-reduced-motion:reduce)"), dark && reduce);
+ assert!(applies("(prefers-color-scheme:light), (prefers-color-scheme:dark)"));
+ assert_eq!(media.with_dark_color_scheme(!dark).with_reduced_motion(!reduce).is_print(), medium.is_print());
+ }
+ }
+ }
+ }
+
#[test]
fn media_type_selects_screen_print_negation_and_query_lists() {
let viewport = (800.0, 600.0);
diff --git a/docs/CDP-media.md b/docs/CDP-media.md
new file mode 100644
index 00000000..c968a92b
--- /dev/null
+++ b/docs/CDP-media.md
@@ -0,0 +1,31 @@
+# Media preference emulation
+
+`Emulation.setEmulatedMedia` accepts `prefers-color-scheme` and
+`prefers-reduced-motion` in its `features` array:
+
+```json
+{"features":[{"name":"prefers-color-scheme","value":"dark"},{"name":"prefers-reduced-motion","value":"reduce"}]}
+```
+
+Color-scheme values are `dark`, `light`, `no-preference`, and the empty string.
+The last two restore the default light preference; the obsolete CSS query
+`(prefers-color-scheme: no-preference)` does not match. Reduced-motion values
+are `reduce`, `no-preference`, and the empty string.
+
+A supplied array replaces both supported preferences. `features: []` clears
+both overrides. Omitting `features` also clears them. Invalid supported values
+or malformed feature entries return an error before changing page state.
+
+Overrides persist across navigation and apply to existing and newly created
+child documents. `matchMedia()` results and change events work with and without
+rendering. Render builds also update CSS media selection, live computed styles,
+geometry, screenshots (including ad-hoc capture viewports), and the preference
+used during PDF print layout.
+The Rust `Page::set_media_preferences(reduce, dark)` method applies the same
+pair of preferences directly.
+
+This does not implement touch emulation or the CDP `media` parameter. Other
+media features retain their existing behavior. The CSS `color-scheme` property
+and automatic darkening are separate from this media-query override. Dynamically
+loaded CSS imports still use the loader's existing fetch-time media filter;
+a preference change does not refetch an import previously skipped by it.
diff --git a/render-repros/checks.json b/render-repros/checks.json
index fec78976..befb9190 100644
--- a/render-repros/checks.json
+++ b/render-repros/checks.json
@@ -1,4 +1,7 @@
{
+ "emulated-color-scheme": [
+ {"name": "default light preference keeps the green block", "color": "#00aa00", "x": 0, "y": 0, "width": 240, "height": 100}
+ ],
"retained-cssom-raster": [
{"name": "CSSOM width and fill survive metadata update", "color": "#246840", "x": 16, "y": 16, "width": 128, "height": 32},
{"name": "updated image and animation callback complete", "color": "#246840", "x": 16, "y": 220, "width": 32, "height": 16},
diff --git a/render-repros/emulated-color-scheme.html b/render-repros/emulated-color-scheme.html
new file mode 100644
index 00000000..94b1cdc8
--- /dev/null
+++ b/render-repros/emulated-color-scheme.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Emulated color scheme</title>
+<style>
+ body { margin: 0; background: #ffffff; }
+ #probe, #scrolled { width: 240px; height: 80px; background: #00aa00; }
+ @media (prefers-color-scheme: dark) {
+ body { background: #202020; }
+ #probe, #scrolled { width: 160px; background: #0055ff; }
+ }
+ @media (prefers-color-scheme: light) {
+ #probe, #scrolled { height: 100px; }
+ }
+ @media (prefers-color-scheme: dark) and (prefers-reduced-motion: reduce) {
+ #probe, #scrolled { height: 60px; }
+ }
+ @media print and (prefers-color-scheme: dark) {
+ #probe, #scrolled { width: 120px; }
+ }
+ #scrolled { position: absolute; top: 1200px; left: 0; }
+</style>
+<div id="probe"></div><div id="scrolled"></div>