Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call .NET objects from Javascript in WP7 WebBrowser control

Is it possible to access local Windows Phone Silverlight C#/.NET objects from Javascript loaded in a WebBrowser control in a WP7 application?

like image 890
thunderboltz Avatar asked Dec 17 '22 09:12

thunderboltz


1 Answers

Not directly, but javascript in the WebBrowser can call out to the application asynchronously by using window.external.notify. The application can detect those notifications using the WebBrowser.ScriptNotify event, and calling back to the javascript using WebBrowser.InvokeScript.

Here's an (untested) example.

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>

Application:

/// <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);
}
like image 84
Richard Szalay Avatar answered Jan 18 '23 23:01

Richard Szalay