How to activate darkmode for the text changed in WkWebViewRenderer?

Xamarin NewBie 121 Reputation points
2021-04-07T02:04:04.613+00:00

I was trying to resize the text in a webView in Xamarin.iOS with a webView-renderer. It works, but my problem is that the dark mode does not work anymore. I have already changed the background of the web view, so it is shown right, but I don't know how to do it with the text.

  public class NavigationDelegat : WKNavigationDelegate
{
    public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
    {
        string Size = "300%"; 
        string text = String.Format(@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '{0}'", Size);

        WKJavascriptEvaluationResult handler = (NSObject result, NSError err) => {
            if (err != null)
            {
                System.Console.WriteLine(err);
            }
            if (result != null)
            {
                System.Console.WriteLine(result);
            }
        };

        webView.EvaluateJavaScript(text, handler);
        webView.Opaque = false;
        webView.BackgroundColor = UIColor.Clear;


    }
}

How to do it? The text is always black, also when darkMode is activated.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,296 questions
0 comments No comments
{count} votes

Accepted answer
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points
    2021-04-07T08:13:50.99+00:00

    Hello,

    Welcome to Microsoft Q&A!

    We can do nothing to support dark mode on WebView programmatically .

    However , there is an easy way to achieve it .

    Just add an @media section to the CSS .

       @media (prefers-color-scheme: dark) {  
           body {  
               background-color: rgb(38,38,41);  
               color: white;  
           }  
           a:link {  
               color: #0096e2;  
           }  
           a:visited {  
               color: #9d57df;  
           }  
       }  
    

    Refer to https://stackoverflow.com/questions/57203909/how-to-use-ios-13-darkmode-for-wkwebview .


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful