【问题标题】:UWP WebView C# event from html来自 html 的 UWP WebView C# 事件
【发布时间】:2017-10-15 01:29:37
【问题描述】:

我可以在 c# 代码中捕获 html 中发生的 JavaScript 事件吗?

考虑以下示例,我有一个带有按钮的 html,在我的应用程序中,我通过 WebView 查看它,并且当单击该特定按钮时,我有一个要执行的 c# 代码。

如何在 c# 代码中捕捉到按钮的点击?

<html>
  <head>
       .......
  </head>

  <body>
       ........
       <button id="idOfButton" name="NameOfButton"></button>
       ........
  </body>
</html>

【问题讨论】:

    标签: webview uwp


    【解决方案1】:

    如何在 c# 代码中捕捉到按钮的点击?

    在 C# 代码中我们无法捕捉到按钮的点击。

    我们应该能够添加WebViewScriptNotify 事件。当页面调用 window.external.notify 并传递字符串参数时,托管的 HTML 页面可以在您的 Windows 应用商店应用中触发 ScriptNotify 事件。

    例如:

    <WebView x:Name="WebViewControl" ScriptNotify="WebViewControl_ScriptNotify" Source="ms-appx-web:///scriptNotify_example.html"/>
    

    后面的代码:

    void WebViewControl_ScriptNotify(object sender, NotifyEventArgs e)
    {
        // Be sure to verify the source of the message when performing actions with the data.
        // As webview can be navigated, you need to check that the message is coming from a page/code
        // that you trust.
        Debug.WriteLine(e.Value);
    }
    

    scriptNotify_example.html 代码:

    <!DOCTYPE html>
    <html>
    <body>
        <p>This is a simple test page for window.external.notify().</p>
        <input id="payload" type="text" value="Payload string" />
        <button onclick="window.external.notify(payload.value)">Call window.external.notify</button>
        <p />
    </body>
    </html>
    

    【讨论】:

    • 用win js写app会有帮助吗?
    • @AravindBelagaje 我们应该能够更改 html。我们也可以在 WinJS 中使用它。
    猜你喜欢
    • 2017-07-15
    • 2017-07-27
    • 2020-10-29
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多