Communicating with a Web Page

,

The WebBrowser.InvokeScript method allows you to call JavaScript functions on a web page, and unlike Silverlight for the desktop, it is not restricted to scripts loaded from the same site as the XAP package. This method allows you to pass the JavaScript function an array of string parameters and is useful when you want to interact with the page, such as by highlighting text, changing the visibility of particular elements, or by adding behavior to a page through subscription to existing client-side events.

Conversely, a web page is able to send messages to your app using the client-side JavaScript method window.external.Notify, which raises the WebBrowser.ScriptNotify event, passing a single string argument.

The example for this section looks at both methods of communication. You see how to pass a string to your app via an HTML button and how to modify the content of a web page from your app.

The sample code for this section is located in the WebBrowser directory of the WPUnleashed.Examples project in the downloadable sample code, and includes the following files:

Image Webpage.html

Image WebBrowserWithScriptingView.xaml

Image WebBrowserWithScriptingView.xaml.cs

We start by looking at the web page, which is loaded into the WebBrowser control at runtime (see Listing 7.7). This web page contains three key elements:

Image A JavaScript function, called Populate, in its head element. We use InvokeScript to call this function from .NET.

Image An HTML div element named textDiv, which is populated using the JavaScript Populate method.

Image An HTML input button, which is used to send the content of the textToSend HTML text box to the Windows Phone app.

LISTING 7.7. Webpage.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="mobileoptimized" content="480" />
    <title>Windows Phone 8 Unleashed</title>
    <style type="text/css"> h1 {color:red}
        div { margin-bottom: 30px; padding: 5px }
        div.received
        {
            border: thin solid #000000;
            font-size: x-large;
            font-weight: bold;
            color: Blue; }
    </style>
    <script type="text/javascript">
        function Populate(input) {
            textDiv.innerHTML = input;
            return true;
        }
    </script>
</head>
<body>
    <div>
        <input name="textToSend" type="text" value="Hi from Page!" />
        <br />
        <input type="button"
               value="Send to app"
               onclick="window.external.Notify(textToSend.value)"/>
    </div>
    <div>Value received from the app:
        <div id="textDiv" class="received" />
    </div>
    <a href="#dummy">A Link</a>
</body>
</html>


The PhoneApplicationPage, WebBrowserWithScriptingView.xaml, contains a WebBrowser control with its IsScriptEnabled property set to true, as shown in the following excerpt:

<Grid x:Name="ContentGrid" Grid.Row="1">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <StackPanel>
        <TextBox x:Name="textBox" Text="Hi from a!" />
        <Button Content="Send to Page"
                Click="Button_Click"
                Style="{StaticResource ButtonStyle}" />
    </StackPanel>
    <phone:WebBrowser x:Name="webBrowser"
        ScriptNotify="WebBrowser_ScriptNotify"
        IsScriptEnabled="True"  Grid.Row="1" />
</Grid>

By default, IsScriptEnabled is false.

The PhoneApplicationPage also contains a TextBox and a button that causes the content of the TextBox to be sent to the web page and placed into an HTML div element.

For the sake of simplicity, the logic for this example is placed in the XAML’s code-beside file (see Listing 7.8). This file loads the web page, which is stored as content within the project and is tasked with calling the WebBrowser’s InvokeScript method when the Send to Page button is tapped, and with responding to the JavaScript window.external.Notify by displaying a message box.

LISTING 7.8. WebBrowserWithScriptingView.xaml.cs


public partial class WebBrowserWithScriptingView : PhoneApplicationPage
{
    public WebBrowserWithScriptingView()
    {
        InitializeComponent();
        DataContext = new WebBrowserWithScriptingViewModel();
    }

    void WebBrowser_ScriptNotify(object sender, NotifyEventArgs e)
    {
        MessageBox.Show(e.Value, "Received Value", MessageBoxButton.OK);
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        StreamResourceInfo streamResourceInfo = Application.GetResourceStream(
            new Uri("WebBrowser/Webpage.html", UriKind.Relative));

        string html;
        using (StreamReader reader
                   = new StreamReader(streamResourceInfo.Stream))
        {
            html = reader.ReadToEnd();
        }
        webBrowser.NavigateToString(html);
    }

    void Button_SendToPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        webBrowser.InvokeScript("Populate", textBox.Text);
    }

...
}


The PhoneApplicationPage uses the WebBrowser’s NavigateToString method to push the loaded HTML into the control.


Note

Calls to NavigateToString must occur after the WebBrowser control is in the Visual Tree. Trying to call NavigateToString in your page constructor raises an InvalidOperationException.


Figure 7.14 shows that when a user taps the Send to Page button, the content of the TextBox control is sent to the web page.

Image

FIGURE 7.14 Sending a string to a web page from a Windows Phone App.

Conversely, when the user taps the Send to App HTML button, the text located in the HTML input text control is sent to the app (see Figure 7.15).

Image

FIGURE 7.15 Receiving a message from a web page within a Windows Phone app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.78.30