0

I am using Webview2 control in a winform. Once I load a particular URL in the browser control, I want to inject additional CSS to bring in a new behavior, which is to add a background color when hovering on any elements in the loaded page.

*:hover {
    background-color: #205081 !important;
}

How do I inject this style code in the currently loaded URL document?

I could accomplish the same through using Javascript functionality as below, but unable to get it running through CSS. Any pointers would be appreciated.

 string jsHoverScript = File.ReadAllText("hoverStyle.js");
 await webBrowser.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(jsHoverScript);
Kim Smith
  • 105
  • 8
  • 1
    To inject CSS into a WebView2 control, you can use the ExecuteScriptAsync method of the CoreWebView2 object. You can pass a JavaScript string that modifies the head of the HTML document and adds a new style element with the desired CSS rules. – Oyvind Andersson Feb 08 '23 at 13:22
  • 1
    Right, you can use any script injection mechanism like CoreWebView2.ExecuteScriptAsync or CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync to inject script. The script should modify CSS in the same manner you would use script to modify CSS in the browser which is covered elsewhere in StackOverflow: https://stackoverflow.com/questions/1720320/how-to-dynamically-create-css-class-in-javascript-and-apply – David Risney Feb 10 '23 at 01:04

1 Answers1

0

According to the doc:

AddScriptToExecuteOnDocumentCreatedAsync adds the provided JavaScript to a list of scripts that should be run after the global object has been created, but before the HTML document has been parsed and before any other script included by the HTML document is run.

When your script is executed, the DOM tree has not been parsed yet, so the css edit does not work. You need to ensure that your script is execute after the DOM tree is parsed.


  • Option1
    Use window.addEventListener in javascript to ensure that you real code is executed after DOM tree parsed.
window.addEventListener('load', 
  function() { 
    // your real logics here
  }, false
);
  • Option2

Use event CoreWebView2.DOMContentLoaded or other alternatives to ensure the C# code executed after the DOM content is parsed. Then use CoreWebView2.ExecuteScriptAsync to execute your real logic

Doc link:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.addscripttoexecuteondocumentcreatedasync?view=webview2-dotnet-1.0.1587.40

https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.domcontentloaded?view=webview2-dotnet-1.0.1587.40

https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.executescriptasync?view=webview2-dotnet-1.0.1587.40#microsoft-web-webview2-core-corewebview2-executescriptasync(system-string)

Bill.W
  • 21
  • 1
  • 5