【问题标题】:带有 XML 输入的 WebView2 ExecuteScriptAsync
【发布时间】:2022-01-23 12:31:39
【问题描述】:

我想使用 ExecuteScriptAsync() 以 XML 文本作为输入来运行 C# 函数。

类似的东西:

var xml = "<?xml version=\"1.0\" encoding=\"UTF - 16\" standalone=\"no\" ?><values>42</values>";
webView2Control.CoreWebView2.Navigate("file:///C:/Users/erezf/AppData/Local/Temp/index.html");
var input = "func(" + xml + ")";
await webView2Control.CoreWebView2.ExecuteScriptAsync(input);

html文件包含函数func:

<script id="test" type="text/javascript">
    function func(xml) { alert(xml); }
</script>

这段代码不起作用,为什么?

【问题讨论】:

    标签: javascript c# html xml webview2


    【解决方案1】:

    传递给 Javascript 函数的 XML 字符串缺少单引号或双引号。 如果您在调试器中查看输入变量,它会如下所示:

    func(<?xml version="1.0" encoding="UTF - 16" standalone="no" ?><values>42</values>)
    

    只需像这样添加单引号:

    var xml = "'<?xml version=\"1.0\" encoding=\"UTF - 16\" standalone=\"no\" ?><values>42</values>'";
    

    【讨论】:

    • 好的,谢谢,对于这个简单的案例,它可以工作,但我真正的 xml 更大,它不起作用。真正的 xml 也包含这个值:“89.356984\n55.000000”我不能把它放在这里,因为它太长了。 ExecuteScriptAsync 中的 \n 字符有问题吗?
    • 好的,我修好了! \n 需要替换为 \\n: xml = xml.Replace("\n", "\\n");现在可以了:)
    【解决方案2】:

    在我的情况下,解决方案是:

    1. add ' ' in the " ".
    2. replace the "\n" with "\\n".
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      相关资源
      最近更新 更多