Tag Archives: WPF JavaScript

Interaction between web browser and JavaScript in WPF

. JS reference

HTML

<button onclick="window.external.Test('called from script code')">
    call client code from script code
</button>

C code in WPF Code:

public void Test(String message)
{
    MessageBox.Show(message, "client code");
}

Communication between WPF and JavaScript requires full trust, so you need to add the following code:

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class MainWindow
{
    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }
}

I do that a lot

//webbrowser sets a context for script callbacks
mywebbrowser.objectForScription = nwe scriptCallBackContext();


[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public calss scriptCallBackContext
{

    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }
}

c#Tune ate JS method

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    string curdir = Directory.GetCurrentDirectory();
    webBrowser.Navigate(String.Format("file:///{0}/test.html", curdir));
    webBrowser.LoadCompleted += (ss, ee) =>
    {
        var jsCode = "fillData('data...');";
        dynamic doc = webBrowser.Document;
        webBrowser.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
    };
}

myscripts.js:

function fillData(data)
{
    //document.getElementById("uname").value = data;
    var oVDiv = document.getElementById("uname");
    //oVDiv.setAttribute("vaue", data);
    oVDiv.value = data;

    //oVDiv.value = data;
    //document.write(data);
}