在WP7 WebBrowser控件中从Javascript调用.NET对象

thu*_*ltz 4 javascript windows-phone-7

是否可以从WP7应用程序中的WebBrowser控件中加载的Javascript访问本地Windows Phone Silverlight C#/ .NET对象?

Ric*_*lay 12

不是直接的,但WebBrowser中的javascript可以通过使用异步调用应用程序window.external.notify.应用程序可以使用该WebBrowser.ScriptNotify事件检测这些通知,并使用回调到javascript WebBrowser.InvokeScript.

这是一个(未经测试的)示例.

HTML:

<html>
<head>
<script type="text/javascript">
    function beginCalculate()
    {
        var inputValue = parseInt(document.getElementById('inputText').value);

        window.external.notify(inputValue);
    }

    function endCalculate(result)
    {
        document.getElementById('result').innerHTML = result;
    }
</script>
</head>
<body>
    <h2>Add 5 to a number using notify</h2>

    <div>
        <input type="text" id="inputText" />
        <span> + 5 =</span>
        <span id="result">??</span>
    </div>

    <input type="button" onclick="beginCalculate()" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

应用:

/// <WebBrowser x:Name="Browser" ScriptNotify="Browser_ScriptNotify" />

private void Browser_ScriptNotify(objec sender, NotifyEventArgs e)
{
    int value = Int32.Parse(e.Value);

    string result = (value + 5).ToString();

    // endCalculate can return a value
    object scriptResult = Browser.InvokeScript("endCalculate", result);
}
Run Code Online (Sandbox Code Playgroud)