UWP Visual C# WebView InvokeScript 更改 CSS 抛出异常

UWP Visual C# WebView InvokeScript to change CSS throws Exception

我试图通过注入 Javascript 函数来更改 WebView(非本地)中已加载网站的 CSS。我找到了这两篇文章 (Article 1, Article 2),但在实施这两个版本后,我总是得到以下异常: System.NotImplementedException {"The method or operation is not implemented."}

到目前为止,这是我的代码:

MainPage.xml

...
  <WebView x:Name="WebView" LoadCompleted="webViewCSS_LoadCompleted"/>
...

MainPage.xaml.cs

...
private void webViewCSS_LoadCompleted (object sender, NavigationEventArgs e)
  {
     addCss();
  }

private void addCss()
  {
     try
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("function setCSS() { ");
            sb.Append("document.getElementsByClassName('app')[0].style.width = '100%';");
            sb.Append("} ");

            string script = sb.ToString();
            WebView.InvokeScript("eval", new string[] { script });
            WebView.InvokeScript("eval", new string[] { "setCSS()" });
        } catch (Exception ex)
        {

        }
    }
...

我不知道它为什么抛出异常。我希望我提供的信息足够了。如果没有,请回复我:-)

预先感谢您的回答

WebView.InvokeScript method may be unavailable for releases after Windows 8.1. Instead, we need to use WebView.InvokeScriptAsync method.

可以参考WebView class,官方文档的备注部分有例子:

you can use InvokeScriptAsync with the JavaScript eval function to inject the content into the web page.