David Eaton
David Eaton

Reputation: 564

C# OpenWebKitSharp .NET 4 - How to call javascript

I am trying to call javascript using OpenWebKitSharp from WinForms with .NET 4

Here is the code I am trying to use.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WebKit;
using WebKit.Interop;
using WebKit.JSCore;
using webkitForm.Properties;

namespace webkitForm
{
    public partial class Form1 : Form
    {

        WebKitBrowser webKitSharpBrowser = new WebKitBrowser();

        public Form1()
        {
            InitializeComponent();

            this.Controls.Add(webKitSharpBrowser);
            webKitSharpBrowser.Width = 600;
            webKitSharpBrowser.Height = 400;


        }


        private void button1_Click(object sender, EventArgs e)
        {
            webKitSharpBrowser.Preferences.AllowPlugins = true;
            webKitSharpBrowser.UseJavaScript = true;
            webKitSharpBrowser.Navigate("http://sandbox.icontact.com");


            webKitSharpBrowser.GetScriptManager.EvaluateScript("alert('An alert from C#!');"); //Call javascript?

        }

    }
}

I can't get javascript to fire for anything... there must be something that I am missing.

Thanks in advance.

Upvotes: 5

Views: 5771

Answers (2)

I tested your code, it IS working, but calling the alert function only triggers an event (WebKitBrowser.ShowJavaScriptAlertPanel), you are responsible for handling that event and showing a message or updating a label, or anything else.

For example:

Browser.ShowJavaScriptAlertPanel += Browser_ShowJavaScriptAlertPanel;

and then handle the event:

private void Browser_ShowJavaScriptAlertPanel(object sender, WebKit.ShowJavaScriptAlertPanelEventArgs e)
{
    MessageBox.Show(e.Message);
}

Upvotes: 0

mario.tco
mario.tco

Reputation: 674

Well, it seems like it can't be done the way you want to:

if you are using .NET 4, calling a function is possible by using:

<webkitbrowser>.GetScriptManager.CallFunction("name", new Object[] { arg1, arg2, ...}); 

If you want to use .NET 2 you can use:

<webkitbrowser>.StringByEvaluatingJavaScriptFromString("name(arguments)")

- Open Webkit Sharp Issues

Upvotes: 3

Related Questions