Oct 122012
 
 October 12, 2012  Posted by at 9:00 pm WinRT  Add comments

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

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”]
<Page
x:Class="InjectCSS.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:InjectCSS"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<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>
</Page>
[/sourcecode]

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]

  4 Responses to “How to invoke javascript functions in a WebView in Windows Store Apps”

  1. Can this be used to return a value back from the JavaScript code?

  2. […] buttons. An AppBar on the top of your app is where you place navigation elements…”How to invoke javascript functions in a WebView in Windows Store Apps (Iris Classon)“Did you know that you can invoke javascript functions in a WebView? I’ve […]

  3. 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)?

  4. 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?

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 6 + 12 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)