Iris Classon
Iris Classon - In Love with Code

How to invoke javascript functions in a WebView in Windows Store Apps

Did you know that you can invoke javascript functions in a WebView?
I’ve made here a very basic example of invoking two functions, one with parameters and one without, each changing the style of html document.
I have a feeling that invoking javascript functions in the WebView can come in handy- feel free to add comments on good usage areas :)

Invoking javascript functions in WebView in Windows Store Apps

The invoke script method is also found on the Windows Phone WebBrowser (Windows Phone equivalent of WebView), and is identical.

As last time, the button style can be found in the standardstyles.xaml resource dictionary but is but here for simplicity. Keep the global styles (or all in general) out of the view.

The View
[sourcecode language=“XML”]

<Border Background="{StaticResource ApplicationPageBackgroundThemeBrush}" BorderBrush="White" BorderThickness="4" Height="400" Width="640" Padding="10">  
<StackPanel>  
    <StackPanel.Resources>  
        <Style x:Key="RefreshAppBarButtonStyle" TargetType="ButtonBase" BasedOn="{StaticResource AppBarButtonStyle}">  
            <Setter Property="AutomationProperties.AutomationId" Value="RefreshAppBarButton"/>  
            <Setter Property="AutomationProperties.Name" Value="Refresh"/>  
            <Setter Property="Content" Value="&#xE117;"/>  
        </Style>  
    </StackPanel.Resources>  
    <WebView x:Name="myWebView" Height="300" Width="600"/>  
    <StackPanel Orientation="Horizontal">  
        <Button x:Name="change" Content="Change fontstyle w. parameters" Click="change\_Click"/>  
        <Button x:Name="change3" Style="{StaticResource RefreshAppBarButtonStyle}" Click="change3\_Click"/>  
        <Button x:Name="change2" Content="Change background no paramteres" Click="change2\_Click"/>  
    </StackPanel>  
</StackPanel>  
</Border>  

The Code
[sourcecode language=“csharp”]
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace InjectCSS
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}

    private const string htmlFragment =  
                "<html><head><script type='text/javascript'>function changeBackground()" +  
                " {var htmlDiv = document.createElement('div'); " +  
                " htmlDiv.innerHTML = '<p>foo</p><style>body {background-color: #d8da3d }</style>';" +  
                " document.getElementsByTagName('head')[0].appendChild(htmlDiv.childNodes[1]);};" +  
                "function changeForeground(color,fontsize){ " +  
                "document.body.style.color = color;" +  
                "document.body.style.fontSize= fontsize;};" +  
                "</script></head><body><div id='myDiv'>Change my color</div></body></html>";  

    protected override void OnNavigatedTo(NavigationEventArgs e)  
    {  
        myWebView.NavigateToString(htmlFragment);  
    }  

    private void change\_Click(object sender, RoutedEventArgs e)  
    {  
        string[] specs = { "black","2.5em"};  
        myWebView.InvokeScript("changeForeground", specs);  
    }  

    private void change2\_Click(object sender, RoutedEventArgs e)  
    {  
        myWebView.InvokeScript("changeBackground", null);  
    }  

    private void change3\_Click(object sender, RoutedEventArgs e)  
    {  
        myWebView.NavigateToString(htmlFragment);  
    }  
}  

}

[/sourcecode]

Comments

Leave a comment below, or by email.
Marco Napoli
10/13/2012 11:41:11 AM
Can this be used to return a value back from the JavaScript code? 
Shubhanu Bhargava
4/6/2013 11:25:45 AM
Hi, I am trying to use the invoke script function to call a javascript function that lists the coordinates of all hyper links on a particular webpage. Here is my javascript function:- 

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);

    return [curleft,curtop];
  }
}

How would I be able to call this function in WebView in Windows 8 and where would this function actually be located (inside the app)? 
Stephen hutchinson
1/24/2014 7:13:30 AM
Another great code example Iris. Clear, concise and to the point. I would like to see an example where you are calling a JavaScript on a remote html page. Is this possible? 


Last modified on 2012-10-12

comments powered by Disqus