fix dark theme issue for plugin web dialog

This commit is contained in:
SoftFever
2026-07-04 22:14:35 +08:00
parent 4e26e7233e
commit f47eee24d3

View File

@@ -80,22 +80,32 @@ std::string host_theme_style()
return s; return s;
} }
// User script that prepends the host theme into the document at document-start, // User script that prepends the host theme into the document, before the plugin's
// before the plugin's own <style>/scripts run (and before first paint). Works // own <style>/scripts affect layout (and before first paint). Works whether the
// whether the plugin page has a <head> or is a bare fragment. // plugin page has a <head> or is a bare fragment.
std::string host_theme_user_script() std::string host_theme_user_script()
{ {
// JSON-encode the style so it is a safe JS string literal regardless of // JSON-encode the style so it is a safe JS string literal regardless of
// quotes/newlines it may contain. // quotes/newlines it may contain.
const std::string style_literal = nlohmann::json(host_theme_style()).dump(); const std::string style_literal = nlohmann::json(host_theme_style()).dump();
std::string js; // On WebView2 a document-start user script runs before <html> exists
js += "(function(){"; // (document.head and document.documentElement are both null), so inserting
js += "if(document.getElementById('orca-host-theme'))return;"; // right away would throw and the theme would silently never apply. Inject at
js += "var css=" + style_literal + ";"; // the first opportunity instead: immediately when a root already exists,
js += "var head=document.head||document.documentElement;"; // otherwise the moment <html> appears as a direct child of the observed
js += "head.insertAdjacentHTML('afterbegin',css);"; // document — still before first paint.
js += "})();"; return "(function(){var css=" + style_literal + ";" R"JS(
return js; function inject(){
var root=document.head||document.documentElement;
if(!root)return false;
if(!document.getElementById('orca-host-theme'))
root.insertAdjacentHTML('afterbegin',css);
return true;
}
if(inject())return;
var obs=new MutationObserver(function(){if(inject())obs.disconnect();});
obs.observe(document,{childList:true});
})();)JS";
} }
// Injected into every page at document start (before the plugin's own scripts). // Injected into every page at document start (before the plugin's own scripts).