开发者

Call .NET objects from Javascript in WP7 WebBrowser control

开发者 https://www.devze.com 2023-04-02 04:51 出处:网络
Is it possible to access local Windows Phone Silverlight C#/.NET objects from Javascri开发者_StackOverflowpt loaded in a WebBrowser control in a WP7 application?Not directly, but javascript in the Web

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


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);
}


if you are using the WebBrowser of WP7 to connect to a remote web site (and this must be the case and WP7 does not host a web server), you can test the web application also from a normal desktop.

Usually if you need to communicate between client-side (JavaScript) and server-side (C# in your case) depending on the specific context and needs you can use some different techniques, for example Page Methods (google for ASP.NET page methods).

it's my understanding that WP7 browser is somewhere between IE8 and IE9 with slightly limited JavaScript engine compared to the both, but something so basic like Page Method should work, I would then test it first from a normal PC then from the Phone and verify if works and if not what breaks.

0

精彩评论

暂无评论...
验证码 换一张
取 消