Skip to main content
 首页 » 编程设计

javascript之如何在 WebView Windows 10 UWP 中调用 javascript

2024年02月05日45zfyouxi

我正在尝试在 WebView 中加载 javascript 以进行一些计算并以字符串形式获取输出。我尝试使用以下代码

string htmlFragment = "<html><head><script type='text/javascript'>" + 
                    "function doubleIt(incoming){ " + 
                    "  var intIncoming = parseInt(incoming, 10);" + 
                    "  var doubled = intIncoming * 2;" + 
                    "  document.body.style.fontSize= doubled.toString() + 'px';" + 
                    "  return doubled.toString());" + 
                    "};" + 
                    "</script></head><body>" + 
                    "<div id = 'myDiv'>I AM CONTENT</div></body></html>"; 
            htmlView.NavigateToString(htmlFragment); 
            htmlView.LoadCompleted += async(s1,e1) => 
              { 
                  string result = await htmlView.InvokeScriptAsync("eval", new string[] { "doubleIt(25)" }); 
                  Debug.WriteLine(result); 
              }; 

更新 根据答案中提供的帮助,我现在可以轻松加载简单的 javascript。但是现在当 javascript 中有多个函数时我遇到了问题,我得到了一个异常(exception)。我正在尝试以下代码

string htmlFragment = @"<html><head><script type='text/javascript'>" + 
                    "function a(){return 10;};" + 
                    "function b(){return 20;};" + 
                    "function c(){return 30;};" + 
                    "return (a()*b()*c());" + 
                    "</script></head><body>" + 
                    "<div id = 'myDiv'>I AM CONTENT</div></body></html>"; 

请提出建议。

请您参考如下方法:

此功能的文档非常糟糕。我花了一些时间弄清楚如何在 UWP WebView

中调用 Javascript

当您第一次查看函数调用 webView.InvokeScriptAsync(string,string[]) 时,您的最初 react 是他们希望将函数名称作为第一个参数,然后将函数参数作为字符串大批。 (mainly because the MSDN documentation says this)

Parameters

scriptName

Type: System.String [.NET] | Platform::String [C++]

The name of the script function to invoke.

arguments

Type: System.String[] [.NET] | Platform::Array [C++]

A string array that packages arguments to the script function.

但是,这是错误的,会导致数小时的头部撞击。真的,他们想要的是第一个参数中的单词“eval”,然后是函数的字符串数组,或者您希望 eval 的命令

   var value = await webViewer.InvokeScriptAsync("eval",  
      new string[]  
      {  
        "functionName(functionParams)"  
      }); 

在使用 Microsoft API 多年后,我确信这不是使用此函数的预期方式,而且有点 hack。不幸的是,如果您想使用 JavaScript,这是我所知道的目前唯一可行的方法。