Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: refresh mpl interactive plots when browser tab becomes visible (#8287)

Myles Scolnicka4fedb0292de
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index 89d10ca447..d820a66556 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -606,6 +606,16 @@ html_content = """
ondownload,
// The HTML element in which to place the figure
document.getElementById("figure"));
+
+ // When the browser tab is hidden (minimized or switched away),
+ // browsers throttle or skip canvas rendering. Any canvas updates
+ // sent by matplotlib while hidden are effectively lost, leaving
+ // blank plots. Re-request the full figure when the tab returns.
+ document.addEventListener("visibilitychange", function() {
+ if (!document.hidden && fig.ws.readyState === 1) {
+ fig.send_message("refresh", {});
+ }
+ });
}
);
</script>
diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.py
index 8094895789..be4e9018aa 100644
--- a/tests/_plugins/stateless/test_mpl.py
+++ b/tests/_plugins/stateless/test_mpl.py
@@ -260,6 +260,25 @@ def test_template_contains_html_structure() -> None:
assert "9000" in result
+def test_template_contains_visibilitychange_refresh() -> None:
+ """Test that template includes visibilitychange listener to refresh
+ figures when the browser tab becomes visible again.
+
+ Regression test for https://github.com/marimo-team/marimo/issues/2092:
+ plots rendered while the tab is hidden appear blank because browsers
+ throttle canvas rendering in background tabs.
+ """
+
+ with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:
+ mock_app_meta.return_value.request = None
+
+ result = _template("12345", 9000)
+
+ assert "visibilitychange" in result
+ assert "document.hidden" in result
+ assert 'send_message("refresh"' in result
+
+
def test_mpl_server_manager() -> None:
"""Test MplServerManager basic functionality"""
from marimo._plugins.stateless.mpl._mpl import MplServerManager