简体   繁体   English

UWP Visual C#WebView InvokeScript更改CSS引发异常

[英]UWP Visual C# WebView InvokeScript to change CSS throws Exception

I am trying to change the CSS of a loaded Website in a WebView (not local) by injecting a Javascript Function. 我正在尝试通过注入Javascript函数来更改WebView(而非本地)中已加载网站的CSS。 I found these two Articles ( Article 1 , Article 2 ) but after implementing both Versions I always get the following Exception: System.NotImplementedException {"The method or operation is not implemented."} 我找到了这两篇文章( 第1条第2条 ),但是在实现这两个版本后,我总是得到以下异常: System.NotImplementedException {“该方法或操作未实现。”}

This is my Code so far: 到目前为止,这是我的代码:

MainPage.xml MainPage.xml

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

MainPage.xaml.cs 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)
        {

        }
    }
...

I dont know why it is throwing an Exception. 我不知道为什么它会引发异常。 I hope the Information that I have given is enough. 我希望我提供的信息足够。 If not please get back to me :-) 如果没有,请回到我身边:-)

Thank you in advance for your answer 预先感谢您的回答

WebView.InvokeScript method may be unavailable for releases after Windows 8.1. Windows 8.1之后的版本可能无法使用WebView.InvokeScript方法 Instead, we need to use WebView.InvokeScriptAsync method . 相反,我们需要使用WebView.InvokeScriptAsync方法

You can refer to WebView class , there are examples in the Remarks part of the official document: 您可以参考WebView类 ,在官方文档的“备注”部分有示例:

you can use InvokeScriptAsync with the JavaScript eval function to inject the content into the web page. 您可以将InvokeScriptAsync与JavaScript eval函数一起使用,以将内容注入到网页中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM